Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Getter & Setter iOS 5

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?

like image 478
alex Avatar asked Jan 04 '12 17:01

alex


People also ask

What is getter () used for?

The getter method returns the value of the attribute. The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values.

What is a getter and setter in C#?

Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer.

What is a getter in Javascript?

Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed.

What are kotlin's properties?

Properties. Properties are the variables (to be more precise, member variables) that are declared inside a class but outside the method. Kotlin properties can be declared either as mutable using the “var” keyword or as immutable using the “val” keyword. By default, all properties and functions in Kotlin are public.


2 Answers

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.

like image 164
jlehr Avatar answered Nov 04 '22 01:11

jlehr


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 } 
like image 36
Jeremy Avatar answered Nov 04 '22 03:11

Jeremy