Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
589 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...