I'm trying to write a very simple piece of data to a .plist file, and I've checked all sorts of code samples, but I'm struggling to get it to work.
First, there's the method to create the file itself and return the path:
-(NSString *)getFilePath{
NSArray *thePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[thePath objectAtIndex:0] stringByAppendingPathComponent:@"events.plist"];
}
Then this is the action I have hooked up to a button. It only inserts a line of dummy data at the moment. or at least, that's what I'm trying to do.
- (IBAction)saveData:(id)sender {
NSArray *data = [[NSArray alloc] initWithObjects:@"E3 Expo", @"05-06-2012", nil];
[data writeToFile:[self getFilePath] atomically:YES];
}
But it doesn't work. I checked the user document's directory via the Organizer in Xcode, and nothing's being created in the "Documents" folder.
Any help would be appreciated. :)
You have to set a dictionary as a root plist object.
[Edit: If you can't see the file, create it with NSFileManager
]
NSError *error;
NSString *plistPath = [self getFilePath];
NSArray *data = [[NSArray alloc] initWithObjects:@"E3 Expo", @"05-06-2012", nil];
NSDictionary *plistDict = [NSDictionary dictionaryWithObject: data forKey: @"array"];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
if(plistData) {
//not necessary
if ([[NSFileManager defaultManager] fileExistsAtPath: plistPath]) {
[[NSFileManager defaultManager] removeItemAtPath: plistPath error: &error];
}
[[NSFileManager defaultManager] createFileAtPath: plistPath contents:plistData attributes: nil];
//necessary
[plistData writeToFile: plistPath atomically:YES];
}
else {
NSLog(error);
[error release];
}
//also release data, since you retained it (sorry, memory management OCD)
[data release];
Based on Apple documentation - scroll to Write Out the Property List
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.