Variable losing its value (iPhone SDK)
Question
I declare a variable in the header file and synthesize it in the implementation. When the view loads (ViewDidLoad) I read a plist file an populate the variable with a value. WIth my NSLog I see that the variable contains the value. However, after the view loads, I have some interaction with the user via a button the executes a method. WIthin that method I check the value again and it is invalid. Why won't the variable maintain its value after the initial load?
program.h
....
NSString * user_title;
...
@property (nonatomic, retain) NSString *user_title;
program.m
@synthesize user_title;
-(void)viewDidLoad{
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
user_title = [array objectAtIndex:0];
[array release];
}
....
-(IBAction)user_touch_screen:(id)sender
{
user_label.text = user_title; //user_title has an invaliud value at this point
....
Solution
user_title = [array objectAtIndex:0]
doesn't retain the variable.
Use this instead:
self.user_title = [array objectAtIndex:0];
That will use the setter that you synthesized, and will retain the value.
OTHER TIPS
You need to retain the value you get out of the array.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow