How does the automatic property synthesized in xcode 4.4 work?

I am new to Objective-C and Xcode, but I was glad to see that Xcode 4.4 automatically synthesizes my properties for me. I suppose this means that I no longer need to enter @synthesize for my properties, and I access them using self.propertyName = @"hi"; , eg.

I am trying to rewrite the example code to better understand it, but this code implements its own getter method. In the sample code, the property is created manually, like @synthesize managedObjectContext = __managedObjectContext; . A custom getter is as follows:

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

In this personal code, I see that he simply uses his manually synthesized accessory to receive and install. I realized in my code, I could just replace __managedObjectContext with self.managedObjectContext , but no. If I do this, I get an error message indicating that I am trying to assign a readonly property. This makes sense because this property is defined as readonly, by another other encoder.

 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; 

So, I understand something about how he manually synthesizes his property, means that if he uses this given setter, he allows you to somehow set the readonly property.

If I manually synthesize a property, as in the code I refer to, everything returns to work, but does not use the new automatic synthesis. If I delete readonly , I can set this property as expected, but I feel like I don’t understand why it has it as read-only, so I bet that something is breaking there.

So, am I using the new auto synthesis incorrectly? How to set this with setter if automatic synthesis doesn't create it for me due to readonly?

thanks

+8
properties ios xcode
source share
1 answer

When Xcode automatically synthesizes, it simulates the following ...

 @synthesize foo = _foo; 

So, you can access the data accordingly using self.foo or object.foo.

However, when implementing access methods (both initializers and dealloc), you must use iVar directly.

Please note: these iVars have two underscores. And they are manipulating in the access method. Use _managedObjectContext and you should be good to go.

+10
source share

All Articles