views:

52

answers:

2

From what I have experienced it seems as if objects cannot be shared data members in objective c. I know you can init a pointer and alloc the object in each method but I cannot seem to figure out how one can say define a NSMutableString as a data member and allow all of the methods to use and modify its data as in c++. Is this true or am I missing something?

+1  A: 

It sounds like you want to synthesize (create getter/setter methods) a property for a member variable. I just found this cheat sheet, go down to the section called, "Properties", should give a quick overview.

Other than that Apple's documentation should give you more info.

blu
Thanks this was just what I was looking for these two lines have save me from great grief:[totalAmount autorelease]; totalAmount = [input retain];I didn't realize the iphone did not have auto garbage collection.
jcb344
+3  A: 

To define an instance variable (member), edit your .h file:

@interface MyClass : NSObject {
    // ivars go here
    NSObject *member;
}
// methods go here
@end

Then, in your .m file, from any instance method (one which begins with -), you can access this variable.

- (void)doThingWithIvar {
    [member doThing];
}

If you want to access the variable from outside the object itself, you'll need accessors. You can do this easily with Obj-C properties:

@interface MyClass : NSObject {
    // ivars go here
    NSObject *member;
}
// methods go here
@property (nonatomic, retain) NSObject *member;
@end

And in the .m:

@implementation MyClass
@synthesize member;
// ...
@end

The @synthesize line creates getter/setter methods for the ivar. Then you can use property syntax:

MyClass *thing = ...;
NSLog(@"%@", thing.member); // getting
thing.member = obj; // setting

(Note that I specified (retain) for the @property; if your member isn't an Objective-C object you won't want that. And if your property's class has a mutable counterpart, you'll want (copy) instead.)

jtbandes