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?
You can call using this:
Without the object, you cannot call an instance variable. However, you can call static method with this declaration:
then in another class you just need to call:
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
@propertyFor example, your string should be declared like:
and then in the implementation:
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