2012-11-09 4 views
0

저는 Xcode를 처음 접했고 정말 도움이 필요합니다.iOS - 보관 처리를 사용하여 파일을 저장하고 파일을 읽는 방법은 무엇입니까?

보관 기능을 사용하여 항목 배열이있는 파일을 저장하고이를 테이블보기에서 읽고 쓰려고합니다.

문제는 앱을 닫은 다음 다시 실행하면 파일에 데이터를 저장할 때 기존 파일을 덮어 쓰고 저장된 데이터가 모두 사라진다는 것입니다.

나는 파일에 데이터를 저장하기 위해이 방법을 사용하고 있습니다 :

-(id)init 
{ 

    if(self = [super init]) 
    { 
     _appSupportPath = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)lastObject]; 

     if (!_appSupportPath) 
      return nil; 

     _repositoryPath = [_appSupportPath stringByAppendingPathComponent:FILE_NAME]; 

     if (_data == nil) 
      _data = [[NSMutableDictionary alloc] init]; 
    } 
    return self; 
} 

-(void)saveToFile 
{ 

    dispatch_queue_t writeQueue = dispatch_queue_create("MyApp:file:write", NULL); 

    NSMutableDictionary *localData = [NSMutableDictionary dictionaryWithDictionary:_data]; 

    dispatch_async(writeQueue, ^{ 
     NSFileManager *fileManager = [NSFileManager defaultManager]; 
     if(![fileManager fileExistsAtPath:_appSupportPath]) 
      [fileManager createDirectoryAtPath:_appSupportPath withIntermediateDirectories:YES attributes:nil error:NULL]; 
     [NSKeyedArchiver archiveRootObject:localData toFile:_repositoryPath]; 
    }); 

} 

어떤 도움을?

잘 모르는 파일을 저장하는 더 좋고/더 쉬운 방법이 있다면 알려주십시오.

미리 감사드립니다.

답변

0

정확하게 저장하십시오. init에서 시작시 읽어보기 :

_data = [[NSKeyedUnarchiver unarchiveObjectWithFile:_repositoryPath] retain]; 

if (_data == nil) 
    _data = [[NSMutableDictionary alloc] init]; 
+0

아, 그 라인이 누락되었습니다. 감사합니다. – Joaocdn

관련 문제