theiOSguy theiOSguy - 2 years ago 63
Objective-C Question

CoreData Model Objects for API

I am using CoreData in my application. I want to abstract out all the CoreData related stuff as an API so that the consume can use the API instead of directly using CoreData and its generated model objects. CoreData generates the managed objects model as following

@interface Person : NSManagedObject


I want to define my API for example MyAPI and it has a function called as


So the consumer of this createPerson API needs to create a Person data object (like POJO in java world) and invoke this API. But I cannot create Person object using

Person *p = [Person alloc] init]

because the designated initializer for this Person model created by CoreData does not allow this type of creation.

So should I define corresponding user facing data object may be PersonDO and this API should take that instead to carry the data into the API implementation?

Is my approach right? Any expert advise if design the API this way is a good design pattern?

Answer Source

You can't use CoreData without dealing with Managed Object Context. You MUST get the person from the context and save it in the context. If you don't want your customer to deal with that, and you don't use different threads in your app,you could create a api,that will call your appdelegate's Managed Object Context, and all the user will need to do is just to call that method.

For example,you could use automaticly generated by Core Data methods to make your API like that:

+ (Person *)newPersonWithAttributes:(NSDictionary *)userInfo {

    // Call the designated initializer, but customer
    // doesn't need to think about managed object context
    return [Person initPesonWithAttributes:userInfo 
                    inManagedObjectContext:[[AppDelegate sharedAppDelegate] managedObjectContext]];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download