EXC_BAD_ACCESS error help
I am new to objective-c and i cannot figure out how memory handling works exactly in this language. Here is some code i wrote from a turorial and i am confused why when i uncomment the [filePath release]
i get an error even though the method is finished. I read some articles on how memory handling works but i cant see what i am doing wrong here.
#import "saaving_dddaaattaViewController.h"
@implementation saaving_dddaaattaViewController
@synthesize field;
-(NSString *)pathOfFile {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsFolder = [paths objectAtIndex:0];// paths[0] = documents directory
return [documentsFolder stringByAppendingFormat:@"myfile.plist"];
}
-(void)applicationWillTerminate:(NSNotification *)notification {
NSLog(@"Saving data...");
NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:field.text];
[array writeToFile:[self pathOfFile] atomically:YES];
[array release];
}
- (void)dealloc {
[field release];
[super dealloc];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad {
NSString *filePath = [self pathOfFile];
if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
NSLog(@"File[%@] does exist.", filePath);
NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
field.text = [array objectAtIndex:0];
[array release];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app];
//[filePath release];// <--- commented out release
[super viewDidLoad];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}开发者_运维百科
@end
Memory Management can be confusing at first. Only release objects that you have created. This is almost only if you use the words alloc, init, retain.
The problem in your case is that you do not actually own the object, it is autoreleased, because you did not alloc, init or retain it. This is fine, but it is not your job to release it, so don't worry about it.
If you get "EXC_BAD_ACCESS" errors later, it might be helpful to use NSZombies to help find where you are releasing incorrectly. They work by placing a "zombie" in memory wherever you release an object so it is easier to tell what the problem is.
EDIT: For example, say you have:
NSString *foo = [[NSString alloc] initWithString:@"foo"];
NSString *bar = [NSString stringWithString:@"bar"];
You would have to release foo, by calling: [foo release];
at some point, but you would not have to release bar because it you did not use alloc to allocate memory for it. This goes for any type of object, not just NSString. A great website explaining this can be found here.
精彩评论