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.
The name of the synthesized getter for property
xyz
is the same as the name of the property, i.e.xyz
. It is notgetXyz
. Only the setter gets prefixed with a "set", becomingsetXyz:
That is why your code
does not compile. Changing to
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 propertystr
.