Custom Getter & Setter iOS 5

2019-01-21 13:08发布

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

.h File

@property (retain, nonatomic) Season *season;

.m File

@synthesize season;


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

    // do some more stuff
}

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

Am I missing something here?

3条回答
地球回转人心会变
2楼-- · 2019-01-21 13:39

If you are going to implement your own getter and setter, you'll need to maintain an internal variable:

@synthesize season = _season;

- (void)setSeason:(Season *)s {
    // set _season
    //Note, if you want to retain (as opposed to assign or copy), it should look someting like this
    //[_season release];
    //_season = [s retain];
}

- (Season *)season {
    // return _season
}
查看更多
狗以群分
3楼-- · 2019-01-21 13:48

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

self.season = s;

is translated by the compiler into

[self setSeason:s];

and

return self.season;

is translated into

return [self season];

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

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;

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.

查看更多
Juvenile、少年°
4楼-- · 2019-01-21 13:50

The thing you’re missing is that the Objective-C compiler basically turns the self.foo = bar syntax into [self setFoo:bar], and self.foo into [self foo]. Your methods, as currently implemented, are calling themselves. As Jeremy suggests, you need to implement them such that the setter actually assigns the value it’s called with to an instance variable on your class and the getter returns the value of that instance variable.

查看更多
登录 后发表回答