在目标c中声明属性(保留)时,set/get方法的默认实现是什么 [英] When declare a property(retain) in objective c, what's the default implementation of set/get method

查看:54
本文介绍了在目标c中声明属性(保留)时,set/get方法的默认实现是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是目标c的新手.我已经阅读了苹果内存管理规则"中的内存管理文档.但是对于如何管理属性的引用,我仍然不太清楚.

I am a newer to objective c. I have read the memory management document on apple's "Memory Management Rules". But I am still not very clear about how to manage reference for a property.

使用保留"注释声明的属性的设置/获取访问方法的默认实现是什么?

What's the default implementation of set/get access methods for a property declared with "retain" annotation?

这是我的假设,请提供一些评论.谢谢.

This is my assuming, please give some comments. Thanks.

@interface SubClass : NSObject {
NSString * _name;
}
... ...
@property (nonatomic, retain) NSString * name;
... ...
@end

-(NSString *) setName {
   return _name;
}

-(void) setName: (NSString *) pName{
    // the correct version of default set method for retain
    if( _name != pName ) {
        [_name release];
        _name = [pName retain];
    }

}

那么dealloc方法可以吗?

So the dealloc method, is this ok?

- (void)dealloc {
    self.name = nil; // or [_name release], _name = nil;

}

推荐答案

正如Matteo Alessani所说,您可以简单地合成该属性以获取默认实现.

As Matteo Alessani says, you can simply synthesize the property to get the default implementations.

作为参考,这是生成的(我通过阅读 Objective-C声明的属性以及将信息拼接在一起):

For reference, this is what's generated (I got this from reading Objective-C Declared Properties and piecing information together):

- (NSString *)name {
    return _name;
}

- (void)setName:(NSString *)aName {
    if (_name != aName) {
        [_name release];
        _name = [aName retain];
    }
}

这篇关于在目标c中声明属性(保留)时,set/get方法的默认实现是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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