Skip to content

Instantly share code, notes, and snippets.

@marshluca
Created November 25, 2010 06:35
Show Gist options
  • Save marshluca/715000 to your computer and use it in GitHub Desktop.
Save marshluca/715000 to your computer and use it in GitHub Desktop.
read and write from documents directory
- (NSString *)documentPathForFile:(NSString *)fileName
{
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentPath = [pathArray objectAtIndex:0];
NSString *filePath = [documentPath stringByAppendingPathComponent:fileName];
return filePath;
// return [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:fileName];
}
- (NSMutableArray *)loadLocalBooksFromDocument:(NSString *)fileName
{
NSString *filePath = [self documentPathForFile:fileName];
NSMutableArray *array = [[[NSMutableArray alloc] initWithContentsOfFile:filePath] autorelease];
return array;
}
- (void)handleDocumentFile
{
NSString *filePath = [self documentPathForFile:@"local.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) {
NSMutableArray *initArray = [[[NSMutableArray alloc] initWithCapacity:0] autorelease];
[initArray writeToFile:filePath atomically:YES];
}
// create a directory
NSString *dir = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"book"];
if (![fileManager fileExistsAtPath:dir]) {
[fileManager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
} else {
// destroy a directory
if ([fileManager isDeletableFileAtPath:dir]) {
[fileManager removeItemAtPath:dir error:nil];
}
}
// read local books
self.localArray = [self loadLocalBooksFromDocument:@"local.plist"];
// write to local books
[self.localArray addObject:@"Book one"];
[self.localArray addObject:@"Book two"];
[self.localArray writeToFile:filePath atomically:YES];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment