Objective-C: How Can I Access String Variable As a Global? - iphone

I am new to iPhone development. I want to access a string variable in all the class methods, and I want to access that string globally. How can I do this?
Please help me out.

Leaving aside the issue of global variables and if they are good coding practice...
Create your string outside of any Objective-C class in a .m file in your project:
NSString *myGlobalString = #"foo";
Then put the declaration in a header file that is included by every other file that wants to access your string:
extern NSString *myGlobalString;
OK, well I can't leave it entirely aside. Have you considered putting your "global" string somewhere else, perhaps inside your application delegate as a (possibly read-only) property?

The preferred methods for creating a global variable are:
Create a singleton class that stores
the variables as an attributes.
Create a class that has class methods that return the variables.
Put the class interface in the
universal header so all classes in
the project inherit it.
The big advantage of method (2) is that it is encapsulated and portable. Need to use classes that use the global in another project? Just move the class with the variables along with them.

You can achieve that by implementing getter and setters in the delegate class.
In delegate .h file
Include UIApplication delegate
#interface DevAppDelegate : NSObject <UIApplicationDelegate>
NSString * currentTitle;
- (void) setCurrentTitle:(NSString *) currentTitle;
- (NSString *) getCurrentTitle;
In Delegate implementation class .m
-(void) setCurrentLink:(NSString *) storydata{
currentLink = storydata;
}
-(NSString *) getCurrentLink{
if ( currentLink == nil ) {
currentLink = #"Display StoryLink";
}
return currentLink;
}
So the variable you to assess is set in the currentlink string by setters method and class where you want the string ,just use the getter method.
All the best

I posted an article about my methodology for doing this:
http://www.pushplay.net/2011/02/quick-tip-global-defines/
This is something I primarily use for notification keys. Creating a globals.h file and adding it to the (your_project_name)_Prefix.pch file will ensure it is accessible globally...

Related

How to use variables created outside of viewDidLoad

Hey I'm very new to Objective C programming and I'm stuck. How come when I create I function, it can't use the variables I created for the labels or textviews, etc. And whenever I call them in the viewDidLoad function, I have to do either self.(variableName) or _(variableName) and it won't let me do that outside of the viewDidLoad function. Is there a way to access them outside of it?
How come when I create I function, it can't use the variables I
created for the labels or textviews, etc.
For one thing, you need to differentiate between a function and an instance method. In Objective-C, classes can have instance variables (variables that are part of an instance of that class) and instance methods (similar to functions that are associated with an instance of that class). Classes can also have properties, which are used rather like instance variables in that they're values associated with an object, but they're accessed through accessor methods. Functions, on the other hand, aren't part of any class. So, a class has an interface where instance variables and methods are declared, like this:
#interface Person : NSObject
{
NSString *firstName;
NSString *lastName;
}
#property (readonly) NSString *fullName;
#property (strong) NSArray *friends;
#property (assign) int age;
- (id)initWithFirstName:(NSString*)first lastName:(NSString*)last;
- (void)addFriend:(Person*)friend;
#end
And also an implementation, like this:
#implementation Person
- (id)initWithFirstName:(NSString*)first lastName:(NSString*)last
{ /* code goes here */ }
- (void)addFriend:(Person*)friend
{ /* code goes here */ }
- (NSString *)fullName
{ return [NSString stringWithFormat:#"%# %#", firstName, lastName; }
#end
Those things in the implementation are instance methods, as denoted by the - at the beginning and the fact that they're defined in an #implementation block. (If they had + instead of -, they'd be class methods instead of instance methods -- I'll let you read about that in the docs.) Properties are accessed by calling an appropriate accessor methods using either normal method calls or dot notation, so if you have:
Person *george = [[Person alloc] initWithFirstName:#"George" lastName:#"Bailey"]
all of these are valid:
NSString *name1 = george.fullName;
NSString *name2 = [george fullName];
george.age = 45;
[george setAge:45];
int years1 = george.age;
int years2 = [george age];
Also, self is a pointer to "the current object". You can use it in instance methods so that objects can call their own methods and access their own properties. For example, the Person class could contain a method like this:
(NSString *)nameAndAge
{
NSString *nameAndAge = [NSString stringWithFormat:#"%#: %d", self.fullName, self.age];
}
Functions, on the other hand, aren't part of any class, use C function syntax rather than Objective-C method syntax, and aren't defined in an #implementation block:
BOOL isMiddleAged(Person* person)
{
return (person.age > 30) && (person.age < 60);
}
You can't use self in function because a function isn't associated with an object, so there's nothing for self to point to. You can, however, use properties of other objects you know about, such as person.age in the example above.
And whenever I call them in the viewDidLoad function, I have to do
either self.(variableName) or _(variableName) and it won't let me do
that outside of the viewDidLoad function.
You must be accessing properties of your view controller. As explained above, self.(variableName) is the way to access properties. _(variableName) refers to a variable (often generated by the compiler) that stores the value of the property. (You shouldn't normally access those variables directly outside initialization methods and -dealloc -- use the property accessors instead.) You can use those properties in any instance method of the class, not just -viewDidLoad. You can also access properties of other objects by replacing self with the name of a pointer to the object, just as I did with person in isMiddleAged().
Seems like your are using autosythesized property. Using Auto Synthesized property you need not to #syhtesize objects.
#sythesize object = _object; will be implicitly implement in this case.
So you can access object using self.object or _object.
You can #synthesize to avoid using objects via self.varName or _varName .You can directly use it using varName.

Global variable in Objective C IPhone

I load a few variables in my appdelegate class. They are declared in my .h file.
I have a global.h file that declares the same vars as extern, such as:
appdelegate.h
NSString *DBName;
global.h
extern NSString *DBName;
I haven't found the pattern yet, but some of the classes I include the global.h but the var is nil.
Any idea what I am doing wrong?
EDIT:
It looks like the vars that are like:
int x;
stick and are available,
but the vars that are pointers get lost:
NSString *Name;
They are all loaded initially from a DB in the appdelegate.
I also tried declaring
char Name[30];
then assigning it and all is good.
Now what?
In a .h:
extern NSString *global;
In a .m somewhere:
NSString *global = #"foobar";
If you need to set the global at runtime, you'll have to do so in a method somewhere; say, applicationDidFinishLaunching:.
Where are you assigning to the global in the NSString case? And when you do are you retaining the value? What do you mean by "lost"?
Note that the variable must not be declared in a .h; the extern goes in the .h, the NSString *global; must be in one and only one .m file.
What kind of variables are your working with? Are they primitives or objects? If they are primitives, you might think about preprocessor define statements rather than global variables.
If they are objects, you may want to create an implementation of your Global class, and use a Singleton instance to serve and set the variables. Something similar to this
#implementation Global
static Global *myGlobal = nil;
+(Global *)sharedInstance
{
if (myGlobal == nil) {
myGlobal = [[self alloc] init];
}
return myGlobal;
}
#end
Then you can call the variables using:
[[Global sharedInstance] variableName]
Problem was the NSStrings were not retained. #xianritchie suggested this in the comment above. I changed the few global strings I have an now all is good.
Thanks all for the help

Using NSMutableDictionary as backing store for properties

I am looking for a shorthand way of setting my properties directly to an NSMutableDictionary that is a instance variable. ie:
KVCModle.h:
#interface KVModel : NSObject {
NSMutableDictionary * data;
}
#property(nonatomic,assign)NSString * string1;
#property(nonatomic,assign)NSString * string2;
#end
KVCModel.m
#import "KVModel.h"
#implementation KVModel
-(id)init
{
self = [super init];
if(self)
{
data = [[NSMutableDictionary alloc] init];
}
return self;
}
-(NSString *)string1
{
return [data objectForKey:#"string1"];
}
-(NSString *)string2
{
return [data objectForKey:#"string2"];
}
-(void)setString1:(NSString *)_string1
{
[data setObject:_string1 forKey:#"string1"];
}
-(void)setString2:(NSString *)_string2
{
[data setObject:_string2 forKey:#"string2"];
}
-(void)dealloc
{
[data release];
[super dealloc];
}
#end
I have tried to override setValue:ForKey: and valueForKey:, but those aren't called, they allow you to directly set properties without using the property syntax.
I have made preprocessor macros to make this work in the past, but I am not interested in typing at all, and would like to avoid as much of it as I can in the future. Is there a way to make this work that I am not familiar with?
I have thought about using NSManagedObject, but I am not sure if I can get what I want out of that.
EDIT:
source
If you're trying to access the properties with code like foo = obj.foo and obj.foo = foo, that's why it doesn't work.
Property-access syntax is synonymous with message syntax; the former is exactly the same as foo = [obj foo], and the latter is exactly the same as [obj setFoo:foo]. There is no KVC code to intercept. Properties are at the language level; KVC is at the framework level.
You'll need to intercept the accessor messages instead. Consider implementing the resolveInstanceMethod: class method, in which you “resolve” the selector by adding a method implementation to the class using the Objective-C runtime API. You can add the same implementation(s) for many different selectors.
For your purpose, have a function or method that examines the selector (using NSStringForSelector and regular NSString-examining techniques) and returns two facts: (1) the property name, and (2) whether it's a getter (foo, isFoo) or setter (setFoo:). Then, have two more methods, one a dynamic getter and the other a dynamic setter. When the selector names a getter, add it with your dynamic-getter method; when the selector names a setter, add it with your dynamic-setter method.
So how do the dynamic-getter and -setter methods work? They'll need to know what property to dynamically get and set, but they also need to take no arguments (getter) or one argument (setter, which takes the value), in order to match the original property-access message. You might be wondering how these generic implementations can know what property to get or set. The answer is: It's in the selector! The selector used to send the message is passed to the implementation as the hidden argument _cmd, so examine that selector the same way as before to extract the name of the property you should dynamically get or set. Then, the dynamic getter should send [data objectForKey:keyExtractedFromSelector] and the dynamic setter should send [data setObject:newValue forKey:keyExtractedFromSelector].
Two caveats:
You may still get complaints from the compiler when you use the property-access syntax to access a “property” that you have not declared in the class's #interface. This is normal and intentional; you're really only supposed to use property-access syntax to access known formal properties. What you're doing, while I found it fun to solve, is technically an abuse of the property-access syntax.
This will only work for object values. KVC does the boxing and unboxing for primitive values, such as integers; since KVC is not involved, no free boxing and unboxing. If you have declared formal properties (see 1), you'll need to introspect them using the Objective-C runtime API, and do the boxing and unboxing yourself with your findings.
This piqued my curiosity, so I went ahead and used Peter Hosey's suggestion of overriding +resolveInstanceMethod: to generate the getters and setters. I posted the resulting object (DDDynamicStorageObject) to a github repository:
https://github.com/davedelong/Demos
What you basically want is your own implementation of the NSManagedObject machinery. I have done something similar. Look here: https://gist.github.com/954035 HTH
(Updated the code to remove the dependency on the non-existant NSString+Utilities.h)
(Added missing ReleaseAndZero() macro)
For the love of all that is sacred - do not use an NSDictionary as a place to stuff every conceivable property of a model object. Ivars are easier to debug, and much much clearer to other developers (including your future self).
If you want to use a dictionary, use a dictionary and some statically defined keys - but if you want a model object, use some ivars
I come to the same problem today just like you. So I find your question posted here.
The answers above used the +resolveInstanceMethod: is a little bit hard for me. :)
My understanding is that as long as we setup the property, we would have getter and setter method, so I use the setter method to implement it.
BDLink.h
#property (nonatomic, strong) NSString *type;
#property (nonatomic, strong) NSString *displayName;
#property (nonatomic, strong) NSString *linkURI;
BDLink.m
- (id)initWithLinkInfoDictionary:(NSDictionary *)linkInfoDict {
for (NSString *key in linkInfoDict) {
const char *rawName = [key UTF8String];
NSString *setMethodString = [NSString stringWithFormat:#"set%c%s:", toupper(rawName[0]), (rawName+1)];
SEL setMethod = NSSelectorFromString(setMethodString);
if ([self respondsToSelector:setMethod]) {
[self performSelector:setMethod withObject:linkInfoDict[key]];
}
}
return self;
}
Hope it would be helpful. My first answer, :)

How do I call methods in a class that I created dynamically with NSClassFromString?

The reason I am doing dynamic class loading is because I am creating a single set of files that can be used across multiple similar projects, so doing a #import and then normal instantiation just won't work. Dynamic classes allows me to do this, as long as I can call methods within those classes. Each project has this in the pch with a different "kMediaClassName" name so I can dynamically load different classes based on the project I'm in:
#define kMediaClassName #"Movie"
Here is the code I am using to get an instance of a class dynamically:
Class mediaClass = NSClassFromString(kMediaClassName);
id mediaObject = [[[mediaClass alloc] init] autorelease];
Then I try to call a method within that dynamic class:
[mediaObject doSomething];
When I then type this into Xcode, the compiler shows a warning that the class doesn't have this method, even though it does. I can see it right there in my Movie.h file. What is going on? How do I call a method from a dynamically instantiated class?
And what if I need to pass multiple arguments?
[mediaObject loadMedia:oneObject moveThe:YES moveA:NO];
Thanks for the help in advance.
you can declare a protocol, like so:
#protocol MONMediaProtocol
/*
remember: when synthesizing the class, you may want
to add the protocol to the synthesized class for your sanity
*/
- (BOOL)downloadMediaAtURL:(NSURL *)url toPath:(NSString *)path loadIfSuccessful:(BOOL)loadIfSuccessful;
/* ...the interface continues... */
#end
in use:
Class mediaClass = NSClassFromString(kMediaClassName);
assert(mediaClass);
id<MONMediaProtocol> mediaObject = [[[mediaClass alloc] init] autorelease];
assert(mediaObject);
NSURL * url = /* expr */;
NSString * path = /* expr */;
BOOL loadIfSuccessful = YES;
BOOL success = [mediaObject downloadMediaAtURL:url toPath:path loadIfSuccessful:loadIfSuccessful];
Well it might be there, but the Compiler doesn't know about it because it assumes that mediaClass is just some Class object, but nothing specific. NSClassFromString() is a runtime function and thus can't give the compiler a hint at compile time about the object.
What you can do:
Ignore the warning
Use [media performSelector:#selector(doSomething)];
And btw, this is wrong:
Class mediaClass; = NSClassFromString(kMediaClassName);
it should be:
Class mediaClass = NSClassFromString(kMediaClassName);
An easier and fancier solution than NSInvocation :)
Class mediaClass = NSClassFromString(kMediaClassName);
if(mediaClass){
id mediaObject = class_createInstance(mediaClass,0);
objc_msgSend(mediaObject, #selector(doSomethingWith:andWith:alsoWith:), firstP, secondP,thirdP);
}
Explanation:
class_createInstance(mediaClass,0); does exactly the same as [[mediaClass alloc] init];
if you need to autorelease it, just do the usual [mediaObject autorelease];
objc_msgSend() does exactly the same as performSelector: method but objc_msgSend() allows you to put as many parameters as you want. So, easier than NSInvocation right? BTW, their signature are:
id class_createInstance(Class cls, size_t extraBytes)
id objc_msgSend(id theReceiver, SEL theSelector, ...)
For more info you can refer the Objective-C Runtime Reference
As Joe Blow says, NSInvocation will help you here, though NSObject has a couple of shortcut methods that you can use: -performSelector:, -performSelector:withObject:, and -performSelector:withObject:withObject:.

Property vs. instance variable

I'm trying to understand how strategies some folks use to distinguish instance vars vs. properties. A common pattern is the following:
#interface MyClass : NSObject {
NSString *_myVar;
}
#property (nonatomic, retain) NSString *myVar;
#end
#implementation MyClass
#synthesize myVar = _myVar;
Now, I thought the entire premise behind this strategy is so that one can easily distinguish the difference between an ivar and property. So, if I want to use the memory management inherited by a synthesized property, I'd use something such as:
myVar = #"Foo";
The other way would be referencing it via self.[ivar/property here].
The problem with using the #synthesize myVar = _myVar strategy, is I figured that writing code such as:
myVar = some_other_object; // doesn't work.
The compiler complains that myVar is undeclared. Why is that the case?
Thanks.
Properties are just setters and getters for ivars and should (almost) always be used instead of direct access.
#interface APerson : NSObject {
// NSString *_name; // necessary for legacy runtime
}
#property(readwrite) NSString *name;
#end
#implementation APerson
#synthesize name; // use name = _name for legacy runtime
#end
#synthesize creates in this case those two methods (not 100% accurate):
- (NSString *)name {
return [[_name copy] autorelease];
}
- (void)setName:(NSString *)value {
[value retain];
[_name release];
_name = value;
}
It's easy now to distinguish between ivars and getters/setters. The accessors have got the self. prefix. You shouldn't access the variables directly anyway.
Your sample code doesn't work as it should be:
_myVar = some_other_object; // _myVar is the ivar, not myVar.
self.myVar = some_other_object; // works too, uses the accessors
A synthesized property named prop is actually represented by two methods prop (returning the current value of the property) and setProp: (setting a new value for prop).
The self.prop syntax is syntactic sugar for calling one of these accessors. In your example, you can do any one of the following to set the property myVar:
self.myVar = #"foo"; // handles retain/release as specified by your property declaration
[self setMyVar: #"foo"]; // handle retain/release
_myVar = #"Foo"; // does not release old object and does not retain the new object
To access properties, use self.propname. To access instance variables use just the instance variable's name.
The problem with using the #synthesize myVar = _myVar strategy, is I figured that writing code such as:
myVar = some_other_object; // doesn't work.
The compiler complains that myVar is undeclared. Why is that the case?
Because the variable myVar is undeclared.
That statement uses the syntax to access a variable, be it an instance variable or some other kind. As rincewind told you, to access a property, you must use either the property-access syntax (self.myVar = someOtherObject) or an explicit message to the accessor method ([self setMyVar:someOtherObject]).
Otherwise, you're attempting to access a variable, and since you don't have a variable named myVar, you're attempting to access a variable that doesn't exist.
In general, I name my properties the same as my instance variables; this is the default assumption that the #property syntax makes. If you find you're fighting the defaults, you're doing it wrong (or your framework sux, which is not the case for Cocoa/Cocoa-touch in my opinion).
The compiler error you're getting is because property use always has to have an object reference, even inside your own class implementation:
self.stuff = #"foo"; // property setter
[stuff release]; // instance variable
stuff = #"bar"; // instance variable
return self.stuff; // property getter
I know that many Cocoa programmers disagree, but I think it's bad practice to use properties inside your class implementation. I'd rather see something like this:
-(void) someActionWithStuff: (NSString*) theStuff {
// do something
[stuff release];
stuff = [theStuff copy];
// do something else
}
than this:
-(void) someActionWithStuff: (NSString*) theStuff {
// do something
self.stuff = theStuff;
// do something else
}
I prefer to do memory management as explicitly as possible. But even if you disagree, using the self.stuff form will clue in any experienced Objective-C programmer that you're calling a property rather than accessing an instance variable. It's a subtle point that's easy for beginners to gloss over, but after you've worked with Objective-C 2.0 for a while, it's pretty clear.
Don,
According to the "rules", you should call Release for every Copy, Alloc, and Retain. So why are you calling Release on stuff? Is this assuming it was created using Alloc, Copy, or Retain?
This brings up another question: Is it harmful to call Release on a reference to an object if it's already been released?
Since Apple reserves the _ prefix for itself, and since I prefer to make it more obvious when I am using the setter and when I am using the ivar, I have adopted the practive of using a prefix of i_ on my ivars, so for example:
#interface MyClass : NSObject {
NSString *i_myVar;
}
#property (nonatomic, retain) NSString *myVar;
#synthesize myVar = i_myVar;
i_myVar = [input retain];
self.myVar = anotherInput;
[i_myVar release]
Since it is quite important to know when you are using the setter and when you are using the ivar, I find the explicitly different name is safer.
In your question, it should be:
self.myVar = #"Foo"; // with setter, equivalent to [self setMyVar:#"Foo"]
and
_myVar = some_other_object; // direct ivar access - no memory management!
Remember that you should not use setters/getters in init/dealloc, so you need to do your direct ivar access (and careful memory management) iin those methods.
what's wrong with simply using
#interface MyClass : NSObject
#property NSString *prop;
#end
nonatomic and retain are not required, retain is the default, and atomic/nonatomic isn\t important unless XCode tells you with a warning.
it is NOT necessary to declare the iVar, one will be created for you named _prop, if you really want to use one (i don't see why to be honest)
#synthesize is NOT required.
when (and you should) using ARC you don't have to bother with retain and release either.
keep it simple !
furthermore, if you have a method like this one
- (void)aMethod:(NSString*)string
{
self.prop = string;
// shows very clearly that we are setting the property of our object
_aName = string;
// what is _aName ? the _ is a convention, not a real visual help
}
i would always use properties, more flexible, easier to read.