tags:

views:

33

answers:

1

I am having following condition:

@interface MyClass:NSObject
    @public NSString *str;
@end

@implementation 
-(id)init{ 

}

@end

Now i want to access str variable outside MyClass in Other Class, (1) Using MyClass Object (2) without using MyClass Object, How can i achieve that ??

+1  A: 

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

vodkhang