Reputation:
I have a NSString object called language and I want to access it from other classes what is the proper way? I tried following steps:
1) I created delegate method and send string via delegate
-(void)setLanguageForController:(NSString *)language {
self.language = language;
}
Console showed this
unrecognized selector sent to instance delegate
2) I created method getCurrentLanguage
static NSString *language;
+(NSString*)getCurrentLanguage {
return language;
}
And access like this
NSString *myLanguage = [[MyView alloc] getCurrentLanguage];
Upvotes: 2
Views: 109
Reputation: 3447
you should declare language
as a property in your class .h
file.
@property (nonatomic, copy) NSString* language;
When you want to set language:
initalize your class instance: yourObj
call: yourObj.language = "whatever"
or [yourObj setLanguage:"whatever"];
Each property declaration ends with a type specification and a name. For example:
@property(copy) NSString *title;
This syntax is equivalent to declaring the following accessor methods:
- (NSString *)title;
- (void)setTitle:(NSString *)newTitle;
read more about objective-C property here
Upvotes: 3
Reputation: 831
You don't need to create your method like setLanguageForController
and getCurrentLanguage
to get and set the your variable like this if you want to access it from other class. You need to create a property
in your interface
file or .h file, it will be public and it provide its getter
and setter
method which you can access from any class by the instance
variable of your class that contains your property
.
You can declare your property
in .h or class interface
file like this:
@property (nonatomic, strong) NSString* language;
To set it's value you can use.
obj.language = @"value"; or [obj setLanguage:@"value"];
To get its value. You need to use same instance
variable like this
NSString *strLanguageValue = obj.language;
Upvotes: 0