Reputation: 10376
I have a view called Cart
. It displays a table of Item
s. These Item
s need to persist, so Item
subclasses NSManagedObject; values like id
, price
, etc. are properties whose accessors are @dynamic
so that they are automagically generated.
I have another view called Favorites
. It displays a table of Item
s, but they don't need to persist. In fact, this view changes whenever the user logs in with different credentials.
The connection between the two views is that the user can add items to his cart from his favorites. A cart can store Item
s from different Favorites
lists. Favorites
lists don't change when the item is added to the cart.
Initially, I made the model for the Favorites
view be an NSArray of NSDictionary objects. When the user adds the item to his cart, I create and save the item in Core Data from the NSDictionary key-value pairs. This approach doesn't look very clean or very DRY. Wouldn't it make more sense to make the Favorites
view's model be an NSArray of Item
s?
So now my intent is to implement the Item
class so that it will represent the Core Data model (NSManagedObject), but also work with the Favorites
view. Being new to Objective-C and iOS development, I really don't know how this would work or look like. It seems that I would need to override the accessors that are magically created for me, but I can't call them at compile time using a super
call... Can anyone give me a rough outline of when it would know to return the NSDictionary data or the Core Data data? In the case that it's Core Data data, how do I maintain the same level of efficiency that the magically-generated accessors would have?
Even better, is there a better implementation that is just as DRY or makes more sense? Or am I trying to combine too much functionality into one class? Is the NSArray of NSDictionary objects the best way to go in this case?
Upvotes: 2
Views: 291
Reputation: 28409
You can specify a result type on your fetch request (object, objectID, count, dictionary).
Also, I would not use NSManagedObjects outside of a MOC. You should either have a separate object that you use for memory stuff, or you can use an in-memory persistent store for those objects... or, you can just create a separate MOC as a child to your main database MOC that you use for your in-memory objects.
The advantage of these approaches is that your code does not have to know whether they are backed to the disk or not.
As long as you do not save the MOC, the changes to those objects will never go to disk.
EDIT
NSFetchRequest *fetchRequest = // create the fetch request...
fetchRequest.resultType = NSDictionaryResultType;
Now, when you make the fetch, instead of getting back an array of NSManagedObject you will get back an array of NSDictionary.
Upvotes: 1