你好,游客 登录 注册 搜索
背景:
阅读新闻

Objective-C类变量的声明

[日期:2013-02-03] 来源:Linux社区  作者:wakin002 [字体:大 中 小]

Objective C中类变量的声明一般有两种方式:

1)instance variable
2)property方式声明

instance variable方式声明如下:

@interface MyClass : NSObject {
    NSString *      _name;
}

如果你不想自己声明set/get函数,则可以用这种方式。

instance variable又有@public,@protected和@private之分,这跟C++是一样的。

例子:

@interface MyClass : NSObject {
 @public
    NSString *      _name;
}

调用:
MyClass * myClass = [[MyClass alloc] init];  // 这里也可以用[MyClass new]来代替。
myClass->_name = @"wang";  // Notice that here you need to use "->" to access.

property方式声明
其实就自动加了set/get函数,如果

@property(retain) NSMutableArray *namearray;

retain表示会自动增加引用计数。相当于

- (void)setNamearray:(NSMutableArray *)namearray
{
    [_namearray autorelease];
    [namearray release];
    _namearray = namearray;
}

注意点:
在init函数中变量的初始化不要用proterty的方式,理由见apple document:


Setter methods can have additional side-effects. They may trigger KVC notifications, or perform further tasks if you write your own custom methods.

You should always access the instance variables directly from within an initialization method because at the time a property is set, the rest of the object may not yet be completely initialized. Even if you don’t provide custom accessor methods or know of any side effects from within your own class, a future subclass may very well override the behavior.

大致意思是说如果你的子类override了set函数,会有很多不可预料的behavior在此set函数中,可能会导致执行错误。所以在init方法中,最好使用instance variable方式来初始化。

linux
相关资讯       Objective-C 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款