Thursday, January 1, 2009

IPhone development - Global variables in Objective C

This one took me few hours, so I hope this post saves someone time.

So while developing our app for iphone, I decided to use static variable (probably a bad design choice, but I wanted to get the concept working and fix the code later). Anyhow. I found that using global static variables in Objective-C is obvious, but only if you know what you are doing.

For a newbie like me, who skimmed the Objective-C manual, and did read that there is something called retain, forgot about it when I actually needed it.

The problem was that I was setting the value in one View, but it was showing up empty on the other side. To add insult to injury, the iphone simulator showed all kind of weird exceptions, which I could not find any explanation yet. For example, it was crashing without any clear explanation. In few times, I saw NSCRArray length selector being invalid as reason for crash.


So, to have a global variable, this is what I did that worked:

In Globals.h:
extern NSString *gProp;

In Globals.m:
NSString *gProp;

In ViewThatHasABigWidgetThatSetsThisGlobalViewController.m:
-(void)someMethod
{ gProp = [textFieldvalue retain]; }

In ViewThatUsesThisGlobalViewController.m:
-(void)someMethod
{ NSString *textFieldValue = gProp; }

No comments: