Custom Getter& Setter iOS 5 [英] Custom Getter & Setter iOS 5

查看:104
本文介绍了Custom Getter& Setter iOS 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ARC覆盖我的ObjC类中的getter和setter。

I want to override the getter and setter in my ObjC class using ARC.

.h文件

@property (retain, nonatomic) Season *season;

.m文件

@synthesize season;


- (void)setSeason:(Season *)s {
    self.season = s; 

    // do some more stuff
}

- (Season *)season {
    return self.season;
}

我在这里遗漏了什么吗?

Am I missing something here?

推荐答案

是的,那些是无限的递归循环。那是因为

Yep, those are infinite recursive loops. That's because

self.season = s;

由编译器翻译成

[self setSeason:s];

return self.season;

被翻译成

return [self season];

摆脱 dot-accessor self 。,您的代码将是正确的。

Get rid of the dot-accessor self. and your code will be correct.

但是,鉴于您的属性 season 且您的变量,此语法可能会造成混淆季节共享相同的名称(尽管Xcode会通过不同地着色这些实体来减少混淆)。可以通过编写显式更改变量名称

This syntax, however, can be confusing given that your property season and your variable season share the same name (although Xcode will somewhat lessen the confusion by coloring those entities differently). It is possible to explicitly change your variable name by writing

@synthesize season = _season;

或者,更好的是,省略 @synthesize 指令一共。现代的Objective-C编译器将自动为您合成访问器方法和实例变量。

or, better yet, omit the @synthesize directive altogether. The modern Objective-C compiler will automatically synthesize the accessor methods and the instance variable for you.

这篇关于Custom Getter& Setter iOS 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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