If you need to access name from outside MyClass methods, you need to define methods to access it. You could just write methods called (NSString*) name and - (void) setName:(NSString*) newName , but it's easier to define properties and synthesize them.
In MyClass.h, you define a property. For strings, you usually copy them:
@interface MyClass : NSObject @property (copy) NSString* name; @end
In MyClass.m, you are still using the interface declaration, with ivar:
@interface MyClass () { NSString *name; } @end
However, you also need to synthesize a new property. This creates methods for extracting and setting the name:
@implementation MyClass @synthesize name = name; @end
As a legend, the underscore is usually underlined at the beginning or end of ivar, so in the interface you will have NSString *_name; , and in the implementation you will have @synthesize name = _name . This helps to avoid the accidental use of ivar when you mean the property.
Now you can access the name property:
MyClass me = [[[MyClass alloc] init] autorelease]; [me setName:@"My name"]; NSLog(@"Name = %@", [me name]);
Objective-C properties are a powerful feature of the language, but they have some quirks that you should learn. Try searching the net for some combination of objective-C, properties, and synthesize.
If you still have errors in the compiler, edit your question using the part of your code where you get access to name .
Dondragmer
source share