How to access public instance variable in Objective-C?
I am having following condition:
@interface MyClass:NSObject
@public NSString *str;
@end
@implementation
-(id)init{
}
@end
Now I want to access str variable outside MyCla开发者_JAVA百科ss in Other Class, (1) Using MyClass Object (2) without using MyClass Object, How can I achieve that?
You can call using this:
MyClass *a;
a.str;
Without the object, you cannot call an instance variable. However, you can call static method with this declaration:
@interface MyClass:NSObject
+ (void)doX;
@end
@implementation
+ (void)doX {
// do whatever
}
then in another class you just need to call:
[MyClass doX];
However, let a public instance variable is not a good practice. The reason is that it will let any class, methods change that instance variable without your control. For example, they can set the NSString *str to nil and then nobody can call anything, or they may forget to do memory management when they call.
A better practice for public variable is using @property
For example, your string should be declared like:
@property (nonatomic, retain) NSString * str;
and then in the implementation:
@implementation MyClass
@synthesize str;
The good thing about property is that compiler will generate gettter and setter methods for you and those setters will handle memory correctly for you.
More about properties here
Sigh, i realise this post is LONG dead but I believe The above answer is incorrect. well the first bit.
Please see the link below. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html#//apple_ref/doc/uid/TP30001163-CH11-SW1
for the above interface to work, you NEED to declare a property for use outside of its class Because the instance variable it is not visible outside its class.
well; You don't NEED to. Doing something like MyClass->str is valid.
Please see this example
@interface Foo : NSObject {
@public NSInteger publicMember;
@private NSInteger aproperty;
}
@property (assign) NSInteger aproperty;`
then the calling class
Foo *f = [Foo new];
f.aproperty = 90;
//f.publicMember = 100; property 'publicMember' not found of type Foo *
f->publicMember = 100;
But as the above post said, you should always use @properties because if var public was a string, you are not retaining the string in any way.
精彩评论