开发者

Why automatically generated Core Data Project contain synthesize for the managedObjectContext?

When we create core data object automatically I see a line

@synthesize managedObjectContext=__managedObjectContext;

However, I do not think we will ever need that line because the code also generate a function

- (NSManagedObjectContext *)managedObjectContext
{
    if (__开发者_如何学编程managedObjectContext != nil)
    {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}

So what am I missing here?

Why synthesize a code that we DO write?


The @synthesize directive

...tell[s] the compiler that it should synthesize the setter and/or getter methods for a property if you do not supply them within the @implementation block.

You're still allowed to create your own implementations.

So why use @synthesize? To associate the variable (storage) called __managedObjectContext with the property (public access point) called managedObjectContext.

Why do this? As Henrik noted, so that you can do lazy setup of the storage.


Because @synthesize managedObjectContext=__managedObjectContext; creates getter and setters for your property (an instance variable) which is valid in the object scope. You're accessing this property while your (lazy) setting it up in the method you mentioned.


from the great core data series on tuts plus: "Because the properties in the interface of the TSPAppDelegate class are declared as readonly, no setter methods are created. The first @synthesize directive tells the compiler to associate the _managedObjectContext instance variable with the managedObjectContext property we declared in the interface of the class. This is a common pattern to lazily load objects."

http://code.tutsplus.com/tutorials/core-data-from-scratch-core-data-stack--cms-20926

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜