Search code examples
iosobjective-csetterundeclared-identifier

Why can't I implement a custom setter and a custom getter at the same time in Objective-C?


My question is pretty simple, so I hope I can get an answer soon.

I'm writing an iPhone app and on one of my objects I have a property called "text". In the implementation file I have written a custom setter:

- (void) setText: (NSString*) text
{
    _text = text;
    self.textField.text = text;
}

This works fine until I try to also implement the getter:

- (NSString*) text
{
    return self.textField.text;
}

After I have written this the compiler starts complaining about the first line in the setter:

_text = text;

saying "use of undeclared identifier _text; did you mean "text" ?

No. I did not mean text. I meant _text. What do you mean oh mighty compiler?


Solution

  • Does the class have an ivar (member variable) called _text of type NSString*? With a manual getter and setter, as opposed to @synthesizing them, you need to explicitly declare one.

    Introduce it in the class interface definition:

    @interface MyClass
    {
        //more ivars
    
        NSString *_text;
    }
    //methods and properties...
    @end