How to use NSManaged object class using NSObject class - ios

I have NSObject class name TrackInfo which contains tracks info like name , artist name,thumb image etc.
I use this class as downloading data and save information to that class after parsing data.
Now I have another tab in which, I have to show some data. This is same kind of data like trackInfo. But when app is in OFFLINE, I have to make NSManagedObject. It is same as trackinfo.
Can I use NSObject class instead of NSManagedObject or Vice-Versa ?
What I basically wants to do is, I have to display track info from one class either Trackinfo (NSObject class) or NSManagedObjectClass which is used to save data when app is in offline.

Short answer is yes, you can. How? You can find a useful discussion Organising Core Data for iOS.
The long answer can be grabbed within the documentation.
NSManagedObject is a generic class that implements all the basic
behavior required of a Core Data model object. It is not possible to
use instances of direct subclasses of NSObject (or any other class not
inheriting from NSManagedObject) with a managed object context. You
may create custom subclasses of NSManagedObject, although this is not
always required. If no custom logic is needed, a complete object graph
can be formed with NSManagedObject instances.
A managed object is associated with an entity description (an instance
of NSEntityDescription) that provides metadata about the object
(including the name of the entity that the object represents and the
names of its attributes and relationships) and with a managed object
context that tracks changes to the object graph. It is important that
a managed object is properly configured for use with Core Data. If you
instantiate a managed object directly, you must call the designated
initializer (initWithEntity:insertIntoManagedObjectContext:).
About your question, it depends on what you need to achieve. If your goal is to perform a sync mechanism between your device and the server, you should set up 1) a model with a TrackInfo entity 2) a Core Data stack that relies on a persistent store like SQLite. Then you should modify TrackInfo to take into account modifications to that entity. For example, a dirty flag property (0 or 1) or a timestamp. When you do a modification on your TrackInfo you update that property. When the connection is restored you need to query against that property and sync with the server. If you choose the timestamp, the server should say what is the latest timestamp to query against.

Related

iOS Managing Domain Model and NSManagedObject Model

I would like to know how can we manage our domain Model and NSManagedObject Model. My scenario is I have to show last 5 comments from coredata which I fetch from coredata manager class, and it returns 5 objects of Comments (:NSManagedObject) object. now I want to to fetch next n number of comments from our server API and will parse them into my domain model object Comments( inherited from NSObject).
Now I have two types of object which logically represents the same object. I want to know best practice/design pattern, how we should handle/implement this.
One obvious solution is to loop through NSManagedObject Model and populate 5 new models of my domain object derived from NSObject and then continue to fetch these objects from my APIManager class. But I want to know the best way if there it is any.
First of all, CoreData is not thread safe, so don’t use those comments objects into the controllers or the views. Isolate core data in a separate layer and transform these objects into a view model or some other form of immutable struct for the view.
Second, you can use a nsfetched result controller in a “provider” class to keep you informed automatically of what are the last 5 comments. A delegate can inform your view of when this provider data change.
You can refresh your server data in background with your api ma manager and when you get the data back, store them in coredata. If you used a nsfetched result controller, you won’t need to do anything else as coredata will automatically notify the object you setup to return you comments

Understanding of NSCoreData and MSManagedObject subclasses

I am learning a bit on NSCoreData and before introducing it some existing projects I have, I would like to validate my good understanding of the core principles.
From what I have understood, NSCoreData make it easier to manage local storage of object (+retrieval after that) by subclassing our Model class from NSManagedObject rather than from NSObject.
Right ?
I have a few questions then. Let's consider I am building a real estate application with as core model object the class Property that can represent an appartment, a house, and all related information. Currently it is managed in my app as a subclass of NSObject.
1) I retrieve the properties from the server through a search query, and have written a initWithJson : method to populate each instance.
Now if I subclass Property from NSManagedObject, I will create my instances by using
+(id)insertNewObjectForEntityForName:(NSString *)entityName
inManagedObjectContext:(NSManagedObjectContext *)context
and I will be still be able to add a populateWithJson: to my class to fill in the properties.
Then I will create a lot of Property instances in the current managedObjectContext, and if I do a save, they will be stored at the physical layer.
If I call again the same webservice, and retrieve the same JSON content, I will recreate the identical managed objects.
How to avoid redundancy with the [managedObjectContext save:&error] call and not to store physically several time the representation of a single real life property ?
2) Let's say I want to store physically only some properties, for instance only the one the user want to have as favorites.
[managedObjectContext save:&error] will save all created / modified / deleted managed objects from the context to the physical layer, and not only the one I want.
How to achieve that ?
Am I supposed to declare another context (managedObjectContext2), move the instance I want to store in that context, and do the save in that one ?
(I mean, I will have a context just to manipulate the object, create instances from the JSON and represents them in UI ... and a second one to actually do the storage)
Or am I supposed to stores all the objects, and add a isFavorite BOOL property , and then fetching using a predicate on that property ?
3) The app has a common navigation pattern : the UITableView lists Properties instance with the minimum information required, and going on a detail view call a webservice to request more information on a specific Property instance (images, full text description).
Is it a good practice for instance to call the webservice only if the property.fullDescription is nil, and then update the object and store it locally with all detailed information, and the next time only to fetch it locally with a predicate on the property.id ?
What about object that might be updated server-side after they have been created?
Thanks for your lights
1) Retrieve the server data into a temporary form (array of dictionaries?), then for each possible property in the array, check to see if you already have an object in Core Data that matches. If you do, either ignore it or update any changed attributes; if not, create a Property object.
2) Decide which things you want to persist in order to support your app's functions. There's no point in creating a managed object for something you don't want to save. Note, though, that Core Data supports sub-classes if you want both Property and FavoriteProperty.
3) Entirely up to your "business rules"…. How often do you need local data to be updated? The only technical consideration might be the guideline to not keep large files locally that can be re-created on demand.

Connect custom class with CoreData

Is it possible to add custom class(not inherited from NSManagedObject) as Entity in CodeData?
Or that is the best way to do if I have Custom class(user profile).
I want to save some users in Core data. Problem is that my Custom class will be changed in future. So, I want that Custom class and CoreData Entity will be inherit from one class. Is it possible to do?
All entities in Core Data are instances of, or instances of subclasses of, NSManagedObject. You have no choice about this.
If you only want to save some user profiles then you should maintain a subclass of NSObject which you usually use and which is able to be created from an NSManagedObject instance (that you have fetched from the data store for that purpose). You will also need a way to create / update an NSManagedObject instance with new details from this user profile class.
If you change the user profile class but not the attributes of the entities in the Core Data model then you don't need to do a migration of the data store.

Discrepancies Between Core Data Editor and NSManagedObjectSublcass

How are discrepancies between the Core Data Editor and the custom NSManagedObject subclass handled by Xcode?
For instance, let's say in the editor I have and Entity called Person with attributes firstName and age. I then create an NSManagedObject subclass of Person from the editor and in the header of the subclass I add the attribute lastName but I don't update the editor with this new attribute.
Depends somewhat on exactly how you define the property, but usually it will be treated like a transient property, so its value will not be set when the object is retrieved from the store unless you write some custom code to set it, nor will Core Data make any attempt to save it to the store. Also you won't be able to use the property in any fetch or sort predicate that results in core data generating sqlite SQL calls.

JSONModel with MagicalRecord

MagicalRecord is a nice library to manage coredata.In my application I have to processes json from web service for managing Json we are using JSONModel. Now the problem is I have to use two separate class to manage magical record and jsonModel.
Is there any way by which I can combine these two?
Thanks in Advance.
What I personally do is to add to all my JSONModel instances a method called:
-(id)mergeWithContext:
Whenever I get a JSON object from the web, JSONModel parses it for me and converts the data to what I need, then if I want to save it to CoreData I just call mergeWithContext: and pass the current context to it.
The further in my mergeWithContext: method I just create a new entity matching the current JSONModel object and copy over all values. (I actually also check whether an entity with the model's ID already exists in CoreData - then I update it, otherwise I create a new instance).
Not too difficult and you get a fair amount of flexibility if you need to add some custom behaviour when the data is saved.
mergeWithContext: returns of course the entity itself, so I can work with it further if I need to.

Resources