iOS Development

Setters & Getters in Objective C


The objective C setters and getters are never used, thanks to the @synthesize keyword bestowed upon us like God’s grace by the good fellows who created the language. Though there is rarely any chance of using it, its good to know how to write it for the apocalypse day when @synthesize is not working (hope it does not come!)

The Getters are easy, simple fellows with minimal code and goes as following:

//MyClass.h file

@interface MyClass: NSObject
    NSString *text;

//MyClass.m file

-(NSString*) text
   return text;

Setters are however a little tricky:

-(void) setText:(NSString *)textValue
    if (textValue != text)
        [textValue retain];
        [text release];
        text = textValue;

Quick Facts:

  1. The above method is the setter and is supposed to set the value to the variable which is passed to it
  2. The “if” condition is put there to avoid unnecessary code execution in case the old value and new value are the same
  3. To make sure “textValue” stays with us for a considerable amount and we do not lose it before proper assignment, we pass “retain” message to increate it’s retain count by 1
  4. We liberate “text” of its old value by passing “release” message to it
  5. Finally we assign the new value to text

2 thoughts on “Setters & Getters in Objective C”

  1. Have you ever considered about including a little bit more than just your
    articles? I mean, what you say is fundamental and everything.
    Nevertheless think of if you added some great
    graphics or videos to give your posts more, “pop”!
    Your content is excellent but with pics and video clips, this
    site could certainly be one of the best in its niche. Superb blog!

    1. Thanks a lot for your comments and I am glad that you like the blog. You are absolutely correct and honestly what is standing between that “pop”-ful blog and me is my absolute laziness and I am truly ashamed of that. I will definitely try to take your advice in to consideration when posting in future. Thanks again!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s