Quote:
Originally Posted by vogueestylee
hi there, I have a code
Code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
page = 0;
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"text" ofType:@"txt"];
NSError *error;
NSString* content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
allLines = [content componentsSeparatedByString: @"\n"];
NSString *myText = [allLines objectAtIndex:page];
textField.text = myText;
}
-(IBAction)next:(id)sender{
page++;
textField.text = [allLines objectAtIndex:page];
}
it is running ok but when click on the next button it crash.. the allLines NSArrazy is "global" defined in .h file.. so what is wrong..? thanx for advices...
|
You need to read up on Cocoa memory management.
the method componentsSeparatedByString returns an autoreleased array. An autoreleased object is one that is temporary, and will go away if nobody retains it (or takes ownership of it.)
The cleanest way to fix your code is to change allLines to a retained property by adding this line to your header:
Code:
@property (nonatomic, retain) NSArray *allLines;
and adding
Code:
@synthesize allLines;
to your .m file.
Then, when you assign a value to allLines, use "property notation":
Code:
self.allLines = [content componentsSeparatedByString: @"\n"];
By saying "self.allLines" you use the setter, which retains the object for you.
Then, in your dealloc method, add the line
Code:
self.allLines = nil;
That triggers the setter to release any old value stored in allLines before your object gets deallocated.