Objective-C variable that is accessible in other classes - ios

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];

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

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;

Related

Difference when declare variable

I have a class below:
#interface Person : NSObject {
NSString *_firstname;
}
#property NSString *firstName;
#end
#implementation Person
#synthesize firstname;
#end
This will declare three variables: firstname, self.firstname and _firstname
What is the difference between the three variables and how do you using with each case?
In modern Objective-C you don't need to create instance variable if you already synthesizing properties.
From what you write it appears that you are confusing properties and ivar.
Properties create getters and setters to your ivars, but they are not ivars, they are methods that access you ivars to set or get their values.
Your class can be sum up like that:
#interface Person : NSObject
#property NSString *firstName;
#end
#implementation Person
#end
At compile time this will ensure that you can access your ivar using methods and name your ivar as _firstName.
Dot notation create access to properties so self.firstName (using ARC and default property option -nonatomic,strong-)calls that method
- (NSString*)firstName
{
return _firstName;
}
While calling self.firstName = #"foo"; calls:
- (void) setFirstName:(NSString*)name
{
if (_firstName == name) {
return;
}
_firstName = name;
}
Underlining implementation could be a little different.
The first one NSString *_firstname; is an instance variable. The #property is a property which is syntesized (you don't have to manually synthesize properties in modern Objective-C). When you declare a property you can access its instance variable with _propertyName or with self.propertyName.
It is up to you whether you declare your variables as instance variables or as properties but it is more common and suggested to declare them as properties (using properties you can have access to getters and setters, which means that you can run code before the value of the property will be set or will be read).
You can chain instance with property using
#interface Person : NSObject {
NSString *_firstname;
}
#property NSString *firstName;
#end
#implementation Person
#synthesize firstName = _firstname;
#end
Both pointers are pointing same instance now.

How to access a property in a public method. "Use of undeclared identifier error"

This probably sounds bare bones basic, but I need help. I'm a bit new to objective-c. So I have a void method that that sets a property. How would I use that same property inside of a public method? Here's the code:
.h
#property (strong, nonatomic) NSString *globalShowKey;
.m
+(NSString *)fileStructure{
NSString *mainDBPath = [PATH stringByAppendingPathComponent:CLIENT_KEY];
NSString *subDirectory = [mainDBPath stringByAppendingPathComponent:globalShowKey];
return subDirectory;
}
Could someone please give me an explanation what the best approach to achieve this? I am so close to achieving this! If I am unclear, please let me know.
You are using self in class method as + in method definition indicates its class method and in class method self represent class not instance of that class.This line is causing trouble
//self represent here class not instance but you need to access instance variable through property
NSString *subDirectory = [mainDBPath stringByAppendingPathComponent:self.globalShowKey];
use - instead of + in method as + indicates class method and - indicates instance method
-(NSString *)fileStructure{
NSString *mainDBPath = [PATH stringByAppendingPathComponent:CLIENT_KEY];
NSString *subDirectory = [mainDBPath stringByAppendingPathComponent:self.globalShowKey];
return subDirectory;
}
Now call this method on class instance
for eg: if this method is defined in class Abc than instead of using [Abc fileStructure]; make object of class Abc
Abc *abc = [[Abc alloc] init];
NSString *fileStructure = [abc fileStructure];
EDIT : You can also make self.globalShowKey as constant string if it is not changing througout application like
NSString *const GlobalShowKey = #"abc"; //write this after #import statements
and than you can append this global key using your previous class method
+(NSString *)fileStructure{
NSString *mainDBPath = [PATH stringByAppendingPathComponent:CLIENT_KEY];
NSString *subDirectory = [mainDBPath stringByAppendingPathComponent:GlobalShowKey];
return subDirectory;
}
and call it by
[Abc fileStructure];

dynamic initialize any objective C class with property

Can we initalize dynamically any Modal class. rather than creating any NSObject class with property values as likes string inside that class.
default we do code as like:
in .h file
#interface MyUser : NSObject
#property (nonatomic, strong) NSString *username,*bio,*website;
#end
in .m file
#implementation InstaUser
#synthesize bio;
#end
To use that we do:
MyUser *sendUser = [[MyUser alloc]init];
sendUser.username = #"JHON";
sendUser.bio = #"abcdcskdfhksfjhfkjsdf";
I Don't want to create so many this type of modal class rather then this just any dynamic method to initalize class property and use it by inline code.
You can use run time feature of objective c class.
Create a single model class and add property to it dynamically at run time:
For more reference :
How can I add properties to an object at runtime?
I think you meant a flexible model object with dynamically declared properties something like this:
MyModel *user = [[MyModel alloc] init];
user.name = #"name";
MyModel *something = [[MyModel alloc] init];
something.dynamicProperty = #"blahblah";
If so, you cannot. Use NSMutableDictionary instead, or consider to generate model classes from a simple config file by some scripts.

How to Pass Parameter to external class method?

I am trying to do very simple operation.
in "TestFile.h" file i've declare property:
#property (nonatomic) NSDictionary *justTest;
and in implementation file "TestFile.m":
-(NSDictionary *)justTest:(NSString *) mystring {
NSLog(#"Here is my string: %#", mystring);
return nil;
}
Now i am trying to call "justTest" from another file. What i am doing:
#import "TestFile.h"
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSDictionary *testFile = [[TestFile alloc] init];
[testFile justTest:#"Hello World!"]
}
This works fine until i'm trying to pass parameter.
if i just execute
[testFile justTest];
it works, but when i try to pass parameter
[testFile justTest:#"Hello World!"];
does not work and the debug message is:
no visible #interface for 'TestFile' declares the selector 'justTest':
What is wrong with me?
You need to make this method public by adding method name to TestFile.h file before #end:
-(NSDictionary *)justTest:(NSString *) mystring;
Just to let you know when you add #property compiler synthesise it (create) two method getter, exactly the same name as your property and setter compiler add 'set' prefix, for example, you declare:
#property (nonatomic) NSDictionary *justTest;
compiler will create two methods:
-(NSDictionary *)justTest {...}
-(void)setJustTest {...}
You need to know that in your code you override the getter method.
Declare your method in TestFile.h file before calling from an external class.
-(NSDictionary *)justTest:(NSString *) mystring;

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

Resources