0

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?

jeremyabannister
  • 3,796
  • 3
  • 16
  • 25
  • When you override both the setter and getter, you need to do @ synthesize manually, it's not done automatically. So, _text doesn't exist until you synthesize it. – rdelmar Jul 28 '14 at 00:54
  • The compiler means you are using an undeclared identifier. _text is not declared. The compiler doesn't declare instance variables for you if you implement both getter and setter, you have to do it yourself. That's because usually you don't need an instance variable. Why do you need one here? – gnasher729 Jul 28 '14 at 07:06

1 Answers1

1

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
Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281