有关使用@property和@synthesize保留属性的问题 [英] Question on retain attribute with @property and @synthesize

查看:91
本文介绍了有关使用@property和@synthesize保留属性的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然不太熟悉Objective-C编码(此问题已证明),并且我认为我还不完全了解@property声明中使用keep属性的工作原理.

I'm still pretty new to Objective-C coding (as evidenced by this question) and I think I'm not completely understanding how using the retain attribute in a @property declaration works.

这是一个示例类:

@interface Foo : NSObject {
    NSMutableArray *myArray; 
}

@property (retain) NSMutableArray *myArray;

我的理解是,将保留属性添加到@property声明中(并在实现文件中使用必要的@synthesize delcaration)将基本上为我完成以下设置和获取操作:

My understanding was that adding the retain attribute to the @property declaration (and using the necessary @synthesize delcaration in the implementation file) will basically do the following setter and getter for me:

- (void)setMyArray:(NSMutableArray *)newArray {
    myArray = [[NSMutableArray alloc] initWithArray:newArray];
    [newArray release];
}

- (NSMutableArray *)myArray {
    return myArray;
}

这是正确的还是我对keep属性的工作方式有误?

Is this accurate or am I mistaken on how the retain attribute works?

推荐答案

添加keep属性将实际生成以下代码:

Adding the retain attribute will actually generate this code:

- (void)setMyArray:(NSMutableArray *)newArray {
    [newArray retain];
    [myArray release];
    myArray = newArray;
}

- (NSMutableArray *)myArray {
    return myArray;
}

在对旧值进行 release 之前在newArray上调用 retain 方法的原因是,如果newArray和myArray是同一对象,则该数组将在其之前被释放再次保留.

The reason the retain method is called on newArray before release on the old value is that if newArray and myArray are the same object, the array will be released before it is retained again.

这篇关于有关使用@property和@synthesize保留属性的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆