iOS find the most common record in core data? - iphone

I want to be able to look through all the attributes of an Entity and find the most popular one. I know it has something to do with NSPredicate, but I can't quite wrap my mind around to achieve it.
One possible solution:
Fetch all the entities and loop through it and sort the attributes into different arrays, from there count the items in the arrays to determine the most popular/common one.
Although this might work I'm just wondering if there's an easier or 'cleaner' way of doing it.
Update:
Thanks #Caleb. Let me clarify, I'm looking for a single attribute value that's most often used by instances of a given entity.

That is really a dirty descision.
I would suggest you to make a new entity, say, AttributeCounter, with two attributes - name and count, and every time you add an attribute to a person, change this entity.
But that would only be good descision if you have a few different attributes and lots of persons. If not, here is another approach, that is quite simple:
Get all the enteties with first attribute not nil,count,add to array
Sort it
Here you are

Related

Core Data Fetch

I have an entity, and I want to fetch a certain attribute.
For example,
Let's say I have an entity called Food, with multiple attributes. I want to select all categories, which is an attribute on each food item. What's the best way to accomplish this in Core Data?
Just run your fetch request and then use valueForKey: to extract all of the attribute values. If your model contains lots of objects, you can set the fetch limit and offset (and sort descriptor) to page through the items. When doing this you should also set the fetch request to not return objects as faults.
Just remembered there is an alternative. You can set the properties to fetch and then set the result type to NSDictionaryResultType. You still need to do the iteration but this will return the minimum data possible.
EDIT: I think I misunderstood your question. It seems that you only want to fetch a property of an object, not the object itself (e.g. the attribute but not the entity)? I don't believe core data is going to work that way...it's an object graph rather than a database, as the person above mentioned. Research how Core Data "faults", automatically retrieving dependent objects as they are needed. I left the advice below in case it still applies, though I'm not sure it will.
You can add a predicate to your search in order to fetch only objects which meet certain criteria; it works like an "if" statement for fetching. Here's Apple's documentation:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSPredicate_Class/Reference/NSPredicate.html
And a tutorial:
http://www.peterfriese.de/using-nspredicate-to-filter-data/
All that said, the necessity really depends on how many objects you're fetching. If it's not causing any performance hit, there's not necessarily anything wrong with fetching a few un-needed objects. Solve problems, in other words--don't "optimize" things that were working fine. If your model contains a ton of objects, though, it could be expensive to fetch them all and you would want to use a predicate.
You can only fetch whole objects, but you can only fetch objects that have a perticlar attribute using nspredicate in your fetch request. See the code snippet in Xcode in the snippet section. Look for fetch request in the find field and drag out the snippet with the nspredicate code. You can set the predicate to only find the objects that satisfy this predicate. Hope this helps!

NSManagedObject identification number

Ok, it seems like I'm asking a noob question (maybe I am and I have just been overlooking important details), but I am looking for a "distinguishing" number/attribute about a generic NSManagedObject that I could use as an ID number (I cannot use the name b/c I want to allow the user to create entities with the same names). If this is not existent please explain how I would recreate this. I understand that I could just add an attribute for this and increment a static variable (ex: currentId) but if I do then I have to consider an entity being deleted then how do I logically place the next inserted entity at that index and then return to the last index.
Core Data does not have the notion of an auto-incremented ID field, keep in mind Core Data is an object graph, not a database. It just happens that a datastore could be backed by a database system, a perfect example is SqlLite.
NSManagedObjectId is kind of like a URL with a GUID to be unique. If you want some sort of auto-incremented id you will have to handle this on your own, there are obviously many different ways you might go about this. You could have a separate entity that stores the last id assigned and read it every time you create a new record, increment the value, use that as your new ID and increment the stored value. This would solve your delete problem if you don't want an ID to be re-used. There are obvious concurrency issues here that you may need to solve. Another approach could be to store the ID in a file on the file system, or in NSUserDefaults, just be sure to take account for concurrency and do not accidentally assign the same ID twice.
There is an objectID method for NSManagedObjects, although I do not believe that they are created in any kind of order.
Personally I would just use and ID attribute. What I don't understand is why deleting would cause any problems. The ID would just sit behind the scenes, there wouldn't be any real reason to show it to the user, right?
It seems like you could use a NSNumber identification row on your entities and then simply keep track of how many objects you have (either by keeping a var or fetching the max value from your storage).
Here I found a few examples that might help you achieve your goal.
link

NSFetchedResultsController depth of fetchedObjects

I have a strange problem here and I want to know, if its related to the lazy loading function.
I do a fetch on my categories. Imagine they have subcategories and these have subsubcategories also. the question right now is: Is the fetchedObjects-Array also collecting the data of the relationship from the subcategories. In short, is it possible to access data something like that: category.subcategory.subsubcategory.name or do i need to make a new fetch on the subcategories first to get access like with subcategory.subsubcategory.name?
I dont get the whole set of the subsubcategories while I am doing it with one fetch. i only get everytime 1 entry instead of 20 or whatever the count should be.
Does anyone have an idea how coredata is handling this? And is it the common way to make a fetchrequest on every new table? Wouldn't it be quite inefficient?
thanks for any help
Use setIncludesSubentities on the NSFetchRequest.
you can also use setPropertiesToFetch to go deep like category.subcategory.subsubcategory.name
propertiesToFetch I believe only works on attributes and to-one relationships however...

Check if attribute exists

Is there better way rather than to fetch with predicate and see the number of results in order to check that the attribute exists when adding it into managed context? I'm trying to make an attribute unique for given entity...
I think you may have scrambled your nomenclature. You don't add attributes to context. You add managed objects which are defined by entities which have attributes. You could be asking about two different types of test.
If you're asking whether a means exist of testing if a managed object already exist with the exact same attributes of the one you planning on inserting, the answer is no. Since entities can be arbitrarily complex and since it takes only literally one bit different to make them logically distinct, there is no means of testing whether two objects are logically identical i.e. have the same attributes and relationships, without fetching them and testing them.
If you're asking whether you can test for a unique value of an attribute of a particular entity then you can. First you fetch on a property using [NSFetchRequest setProperty:] and then set you're predicate for the sought value. When walking relationships, you can use the Set and Array Operators to find managed objects with unique values.

Core Data: Inheritance, STI or otherwise?

I can't seem to find any information in the documentation or via Google on this, but if there is something, a pointer to it would be great.
In my app, I have a Thing as a core data class. I intend to have that Thing contain many Items which has a bunch of fields in it, like order and created_date and so forth. However, there are a variety of Item types, each with their own set of fields. Ideally, I'd like to create several subclasses of Item, so that I can access all the items together in a single array or something.
In Rails, I'd use STI for this. Does Core Data support similar behaviour?
Thanks!
You can create an Item abstract entity and then have each of your unique items extend from it. Keep the relationship in the abstract so that your Thing can see all of them.
Be warned, however, that under the hood, all of those children will actually be put into a single wide table so you will need to test for performance considerations.