@synthesize a=_a

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值