Question

Hi I'm a newbie in Objective-C programming. Today I was writing a program and I'm quite confused with the way it behaves. Here is the program :

#import <Foundation/Foundation.h>
@interface MyClass:NSObject
{
    NSString * str;
}
@property NSString * str;
@end;

@implementation MyClass
@synthesize str;
@end

int main()
{   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc]init];
    MyClass * obj = [[MyClass alloc]init];
    [obj setStr: @"hello"];
    /* the following lines of code will give error if not commented but why it is                    
     resulting in error  ?????
      NSLog(@"Str = %@",[obj getStr]); // **gives error if not commented** 
      **or**
      NSString * temp;
      temp = [obj getStr]; // gives error
      NSLog(@"%@",temp);
    */
    NSString * temp;
    temp = obj.str;
    NSLog(@"%@",temp); // works just fine 
    [pool drain];
    return 0;
}

In main function when I try to print the str value using getStr a synthesized accessor it gives me error. Why so? Are we not allowed to use synthesized getter for NSString or am I not using the getter in a correct way?? But still the synthesized setter [obj setStr] sets the value for NSString type. I saw some answers here and there for this kind of questions on stack overflow but I really din't understand the answer which were provided there so please explain this in a simple manner for me. Many thanks.

Was it helpful?

Solution

The name of the synthesized getter for property xyz is the same as the name of the property, i.e. xyz. It is not getXyz. Only the setter gets prefixed with a "set", becoming setXyz:

That is why your code

NSLog(@"Str = %@",[obj getStr]);

does not compile. Changing to

NSLog(@"Str = %@",[obj str]);

will fix the problem.

Note: when you let Xcode synthesize a property for you, a variable to "back" that property is also created. You do not need to declare an instance variable str in addition to the property str.

OTHER TIPS

This is not getter method call temp = [obj getStr];. Getter method is trigger by either [obj str]) or dot notation obj.str. But you can define getStr, if you do, then use as you have done.

Another way to access getter and setter of a property:

//getter
NSLog(@"Str = %@",self.str);

//setter
self.str = @"hello";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top