开发者

Object as a data member in Objective C

开发者 https://www.devze.com 2023-01-05 13:18 出处:网络
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

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 metho开发者_如何学运维ds to use and modify its data as in c++. Is this true or am I missing something?


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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消