adit
adit

Reputation: 33644

custom setter for NSString

I have a NSString called fontType

and I am trying to have a custom setter for it:

- (void) setFontType:(NSString *) fType
{   
    if (self.fontType != fType){
        [fontType release];
        self.fontType = [fType retain];
        //some more custom code
    }
}

Is there any issue with this?

Upvotes: 1

Views: 1268

Answers (2)

QED
QED

Reputation: 9913

A few things that stand out for me:

  • do not use self. inside of custom accessors. access the variable directly
  • it's better use copy semantics for properties of a type that has a mutable subtype
  • be careful with whatever is // some more custom code

My personal style preferences are like so:

-(void)setFontType:(NSString *)fontType_ {
   if (fontType == fontType_) return; // get out quick, flatten the code

   [fontType release];
   fontType = [fontType_ copy];

   // some more code
}

Cocoa with Love has a good article on this topic. It's worth a read.

Upvotes: 4

EmilioPelaez
EmilioPelaez

Reputation: 19884

When you do self.fontType = newFontType, you are doing [self setFontType:newFontType] (just with a different syntax), this means you are calling the method inside itself.

This is called recursion, but in this case, you don't have a base case in which the method will stop calling itself, so my guess is that this method will call itself until the app crashes. In short, recursion is not something you want here.

Just replace self.fontType = [fType retain] with fontType = [fType retain] (Assuming the var linked to the fontType property is called fontType as well).

PS. At the end of the question you asked

Is there any issue with this?

If you didn't try this, then you shouldn't even be asking that here on StackOverflow, and if you did try it, then you should have realized that this method didn't work, so that last line is pretty meaningless. Just saying.

Upvotes: 0

Related Questions