How does the automatic property synthesize in xcode 4.4 work?

走远了吗. 提交于 2020-01-02 02:46:26

问题


I'm new to Objective-C and XCode, but I was happy to see that XCode 4.4 automatically synthesizes my properties for me, now. I figure this means that I no longer have to type out @synthesize for my properties, and that I get to access them using self.propertyName = @"hi";, for example.

I'm trying to re-write some example code so that I can understand it better, but this code implements a custom getter method. In the example code, the property is manually synthesized, as @synthesize managedObjectContext = __managedObjectContext;. The custom getter looks like this:

- (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 person's code, I see he's just using his manually synthesized accessor to both get and set. I figured in my code, I could just replace the __managedObjectContext with self.managedObjectContext, but nope. If I do this, I get an error telling me that I am trying to assign to a readonly property. This makes sense, because that property is defined as readonly, by this other coder.

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

So, I figure something about how he's manually synthesizing his property means that if he uses that specified setter, it allows him to set a readonly property somehow.

If I manually synthesize the property, like in the code I am referencing, everything goes back to working, but that's not making use of the new automatic synthesize. If I remove the readonly, I can set this property, as expected, but I feel like I'm not understanding why he has it as readonly, so I bet I'm breaking something there.

So, am I mis-using the new automatic synthesize? How do I set this using the setter, if the automatic synthesize is not creating it for me, because of readonly?

Thank you


回答1:


When XCode auto-synthesizes, it simulates the following...

@synthesize foo = _foo;

So, you can access the data appropriately with self.foo or object.foo.

However, in the implementation of accessor methods (and initializers and dealloc), you should use the iVar directly.

Note, those iVars have two underscores. And, they are being manipulated in the accessor method. Use _managedObjectContext, and you should be good to go.



来源:https://stackoverflow.com/questions/11752443/how-does-the-automatic-property-synthesize-in-xcode-4-4-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!