@synthesize a=_a

来源:互联网 发布:回转企鹅罐 知乎 编辑:程序博客网 时间:2024/04/30 04:39

An object declared like this:

@interface Example : NSObject {    NSObject *_a;}@property (retain) NSObject *a;@end

And implemented like this:

#import "Example.h"@implementation Example@synthesize a = _a;@end

Makes an ivar named _a and two accessor methods in the Example object. The accessor methods have these signatures:

- (NSObject *)a;- (void)setA:(NSObject *)theA;

Method a returns the object in the _a ivar. Method setA releases the object stored in _a (if not nil), assigns the parameter to _a, and sends the parameter an retain message.

These methods may also be access through dot notation:

Example *e = [[Example alloc] init];// These two are equivalent. e.a = anotherNSObject;[e setA:anotherNSObject];// These two are equivalent.anotherNSObject = e.a;anotherNSObject = [e a];

Accessing _a directly will circumvent the accessor methods, potentially causing problems such as memory leaks. For example if _a holds the only reference to an object and a new object reference is assigned to _a the old object will become a leaked object.

To directly answer your two questions:

You may use either a or _a. In most cases you'll be better off using _a when reading the value within methods of the object declaring a, and setA (or a in dot notation) when setting the value of_a. Objects that use Example objects should use the accessor methods (with or without dot notation).

The complier does not automatically make a connection between ob and _ob declarations. In this example the @synthesize a = _a; statement makes the connection with the optional = _a. The ivar may have any name. @synthesize a = george; would also be valid. Without the = _a part the compiler would make an ivar named a and two accessor methods.

One further note: You may omit the declaration of _a in the interface, which restricts the scope of the_a ivar to just the implementation of the Example object. Adding the optional = _a to the@synthesize statement will make as ivar of the same type as the property declared in the interface.

原创粉丝点击