I have the following code where I am passing the value of buttonString (an NSString) to another view controller. the app crashes when buttonString = imageName; is set and then called on the other view controller.
in the .h file of the FirstViewController before the @interface:
extern NSString* buttonString;
in the .m file of the FirstViewController before the implementation:
NSString* buttonString = nil;
and here’s the code:
NSString *imageName = [NSString stringWithFormat:@"myImage_%d.png", selectNum + 1 ];
NSLog(@"imageName is %@", imageName);
[buttonImage setImage:[ImgUtil image:imageName]];
buttonString = imageName;
NSLog(@"buttonString %@", buttonString);
the problem arises in the SecondViewController when this is called:
NSLog(@"button Message is %@", buttonString);
if I remove the buttonString = imageName; from the FirstViewController then the app doesn’t crash.
thanks for any help.
This is happening because
buttonStringis pointing to a released object.From your code segment, imageName is an autoreleased NSString. When you say
buttonString = imageName;it just pointsbuttonStringto the same address asimageName. After this method is over,imageNamegets released and so does the memory to whichbuttonStringwas pointing too.This is why the app crashes when you refer to
buttonStringin NSLog.Ideally, you shouldn’t be sharing data using global variables like this in Objective C. But if you just want to make this work you need to allocate memory to
buttonStringwhen it’s used first. Make sure you do release it when it is of no use later.NOTE: It still will be a bad way to do things.