-1
  1. I have n number of object of an entity.

  2. I want to fetch 30, random object from the same entity.

    I'm using core data, swift 3. Could anybody help me to solve this problem?

Thanks,

Community
  • 1
  • 1

1 Answers1

3

This is going to require an extra step, because Core Data doesn't have any built-in support for a random selection. You'll need to have some unique attribute, select your own random subset of values for that attribute, and then get the managed objects with those values.

First, you need a managed object property that has unique values. Any property will do, but numeric properties will work faster. Let's say for example you have an integer property called myUniqueID that has unique values.

  • Do a fetch request to get all current values of this property. You only want values of this specific property, so set the fetch result type to NSFetchRequestResultType.dictionaryResultType and set the fetch request's propertiesToFetch to include only myUniqueID. The result will be an array of dictionaries, each containing a single value of myUniqueID.
  • Add your own logic to choose 30 random values from this result. Collect them in an array.
  • Do a second fetch request, this time fetching managed objects instead of dictionaries. If your array of random IDs is called uniqueIDArray, use a predicate of something like NSPredicate(format: "myUniqueID in %@", uniqueIDArray)
Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • Thanks, is there any other way? – Deepak Kumar Sahu Nov 15 '17 at 07:58
  • 1
    @DeepakKumarSahu One minor variation on Tom’s solution would be to specify .managedObjectIDResultType, which will give you an array of NSManagedObjectIDs from which you can randomly select 30. The corresponding predicate for the subsequent fetch would then be “SELF IN %@“. This avoids changing the model, but still requires two fetches. – pbasdf Nov 15 '17 at 13:36
  • @DeepakKumarSahu Probably but there's not likely to be a simpler one. – Tom Harrington Nov 15 '17 at 15:37