Elton's Blog

iPhone/Mac Objective-C内存管理教程和原理剖析(三)@property (retain)和@synthesize的默认实现

by on 七.29, 2010, under iPhone, Mac

三 @property (retain)和@synthesize的默认实现
在这里解释一下@property (retain) ClassB* objB;和@synthesize objB;背后到底发生了什么(retain property的默认实现)。property实际上是getter和setter,针对有retain参数的property,背后的实现如下(请参考附件中的memman-getter-setter.m,你会发现,结果和memman-property.m一样):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@interface ClassA : NSObject
{
         ClassB *objB;
}
 
-(ClassB *) getObjB;
-(void) setObjB:(ClassB *) value;
@end
 
@implementation ClassA
-(ClassB*) getObjB
{
         return objB;
}
 
-(void) setObjB:(ClassB*) value
{
         if (objB != value)
         {
                   [objB release];
                   objB = [value retain];
         }
}

在setObjB中,如果新设定的值和原值不同的话,必须要把原值对象release一次,这样才能保证retain count是正确的。
由于我们在class内部retain了一次(虽然是默认实现的),所以我们要在dealloc方法中release这个成员变量。

1
2
3
4
5
-(void) dealloc
{
         [objB release];
         [super dealloc];
}

摘自:http://www.cnblogs.com/VinceYuan





:, , ,

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...