tags:

views:

40

answers:

2

I am work on a simple program in which I split a string and a user global, I use the following code for splitting the string.

NSString *GlobleStr;//globale variable

    //===============
NSString *xmlParsingResult=@"Apple,iphone";
NSArray *array = [xmlParsingResult componentsSeparatedByString:@","];
NSString *StrResult = [NSString stringWithFormat:@"%@", [array objectAtIndex:0]];
GlobleStr =[NSString stringWithFormat:@"%@",[array objectAtIndex:1]];
NSLog(@"cmd %@",StrResult);
NSLog(@"value%@",GlobleStr);

my code can split the string and o/p is cmd:Apple value:iphone

but my problem is that as soon as I call another xib then my global variable will be empty or nil and the application will crash ( it throws error like Variable is not cfstring).

Any suggestions?

+2  A: 

It's because NSString's +stringwithFormat: method returns an autoreleased string. In a local variable this is often what you want to prevent memory leaks (otherwise you have to manually release the string when you're done with it). The problem here is that the string in GlobleStr is getting released by the autorelease pool sometime after you assign it, then when you try to access it in another place you get a crash.

The fix is this: GlobleStr = [[NSString stringWithFormat:@"%@",[array objectAtIndex:1]] retain];

As an aside, you can just do this instead:

GlobleStr = [[array objectAtIndex:1] retain];

I strongly recommend reading Apple's documentation regarding memory management in Cocoa: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html .

Finally, without seeing your code I can't say for sure, but I'd be curious to know why you're using a global variable for GlobleStr. It's a blanket statement, and there are certainly exceptions, but when programming in Cocoa there's probably a better way to structure your code.

Andrew Madsen
+1  A: 

You need to retain your global, otherwise it will be deallocated when the autorelease pool drains:

GlobleStr = [[NSString stringWithFormat:@"%@", [array objectAtIndex:0]] retain];

Remember to release it later on when you're done -- in particular, before assigning any other value to it.

walkytalky