开发者

question about retain attribute in properties

The objective C docs say this about retain attribute in properties:

retain Specifies that retain should be invoked on the ob开发者_高级运维ject upon assignment. (The default is assign.) The previous value is sent a release message.

I thought I understood properties and attributes until I saw something like this in the UITableViewCell reference guide:

@property(nonatomic, readonly, retain) UIImageView *imageView

then reading the above really confused me.

my questions:

1) suppose I have:

@interface SomeClass: NSObject {
   NSString *b;
}
@property (nonatomic,retain) NSString *b;
@end

then in the implementation file:

@implementation SomeClass
@synthesize b;

- (id) initWithSomeString(NSString *c) {
    if (self = [super init]) {
        b = c;
     }
}
@end

this will not increment the retain count of the object pointed to by "b" correct? I am confused now about this because objective C doc says that:

retain Specifies that retain should be invoked on the object upon assignment. (The default is assign.) The previous value is sent a release message.

2) If the above is correct, then the retain attribute only increments retain count when the setter is called correct?

3) I have heard in some places that it isn't good to call the setter method of an object in its own initializer. Why? To me if you it isn't good to do that then one would have to do:

NSString *b = [someOtherString retain];

which seems odd considering you have made a property out of b.

4) Having @property (retain, readonly) SomeObject *t; like in the UITableViewCell example above is also confusing. "readonly" means no getter is synthesized. If my understanding of "retain" is correct (that is it only happens in the setter), then this seems really contradictory.


b=c; will not increment the retain count, but

self.b=c; will increment the retain count.

2) yes, the second calls the setter, so it increments the retain count. The first is a primitive, C assignment.

3) actually, it should be:

b = [someothestring copy];

you've just declared a local, overriding access to your instance variable, assigned it a (now over-retained) object, and leaked when you leave this function.

4) retain, because internally, the object is retained. read-only, because code that uses this class isn't allowed to set that field, only the class is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜