3

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?

user4951
  • 32,206
  • 53
  • 172
  • 282
  • Which project template are you using? I don't see the @synthesize directive when I create a blank Core Data project and it does seem superfluous to me. – omz May 16 '11 at 17:26

3 Answers3

2

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • I noticed that the __managedObjectContext is sort of essensial for lazy loading. I missed that. Without it, you can't just "assign" managedObjectContext directly because the property is read only. So you need an actual private variable with different name than the original variable name. – user4951 May 20 '11 at 04:38
1

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

skinsfan00atg
  • 571
  • 1
  • 3
  • 19
1

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.

Henrik P. Hessel
  • 36,243
  • 17
  • 80
  • 100
  • Yes but what to synthesize? First there is no setter given that it's read only. The only thing to synthesize would be the getter. However, we defined the getter. So what more to synthesize? – user4951 May 16 '11 at 14:21