본문 바로가기

개발/App Developer

NSDictionary

정확히 말하면 NSDictinary를 파일에 저장하고, 파일에서 읽는 방법이다. 그런데 여기서 잠깐 아이폰 앱 샌드박스에 데이터 저장하는 방법에 대한 이해가 선행되어야 한다.


 
아이폰 앱을 설치하면 해당 샌드박스에 몇 개의 디렉토리가 좌측 그림처럼 생긴다. 

Library 디렉토리에는 PLIST 파일로 저장된 설정값을 담은 Preferences 디렉토리가 있다. 

Caches 디렉토리에는 실행 시 저장되는 캐시 데이터가 들어 있다. 이 캐시 데이터는 아이폰을 아이튠즈에 연결했을 때에는 백업 대상에서 제외된다. 

tmp 디렉토리는 앱이 실행되는 동안 필요한 임시 파일이 담긴다. 임시 파일들은 실행이 종료되면 자동으로 삭제된다.

Documents 디렉토리에는 사용자 데이터가 담겨 있다. 사용자 데이터는 아이튠즈 동기화 대상이므로 기기를 복원하면 데이터가 그대로 복구된다. 
그러므로 PLIST 파일이나 사용자 데이터를 Documents 디렉토리에 저장할 수 있다.

그러기 위해서는 다음과 같이 방법으로 Documents 디렉토리 경로를 얻어야 한다.

 
 
 
 
 

 

[Xcode에서 Core Data를 사용할 경우 템플릿 코드]

- (NSString *)applicationDocumentsDirectory {

return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

}


// 또는 


- (NSString *)applicationDocumentsDirectory {

return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

}


위 내용이 숙지되었다면, 다음과 같이 코드를 작성하면 된다.

// 먼저 빈 "test" 파일을 생성해 놓아야 한다.

- (void)save {

NSLog(@"생성...");

  NSDictionary *test;

// 객체와 키 추가.

// [test setObject:[self 프라퍼티] forKey:@"키"];

// ...

NSString *writableFilePath = [self createEditableCopyOfFileIfNeeded:[NSString stringWithString:@"test"]];

if (![test writeToFile:writableFilePath atomically:YES]){

NSLog(@"쓰기 에러);

}


- (void)load {

NSLog(@"로딩...");

NSString *writableFilePath = [self createEditableCopyOfFileIfNeeded:[NSString stringWithString:@"test"]];

test = [NSDictionary arrayWithContentsOfFile:writableFilePath]; 





- (NSString *)createEditableCopyOfFileIfNeeded:(NSString *)_filename {

    // 파일 존재 여부 확인.

    BOOL success;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSError *error;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *writableFilePath = [documentsDirectory stringByAppendingPathComponent: _filename ];

    success = [fileManager fileExistsAtPath:writableFilePath];

    if (success) return writableFilePath;

// 사용자의 Documents 디렉토리에 파일이 없는 경우, 앱의 resources 디렉토리에서 기본 데이터 파일을 가져온다.

NSString *defaultFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: _filename ];

    success = [fileManager copyItemAtPath:defaultFilePath toPath:writableFilePath error:&error];

    if (!success) {

NSLog([error localizedDescription]);

        NSAssert1(0, @"Failed to create writable file with message '%@'.", [error localizedDescription]);

    }

return writableFilePath;

}


NSDictionary
 
key와 value의 집합으로 데이터를 저장하는 객체
key는 객체 내에서 유일해야 한다.
생성된 객체를 변환할 수 없다. (NSMutableDictionary 는 변환가능)
 
metod
 
-(id) initWithDictionary : (NSDictionary*) otherDictionary;
다른 Dictionary 객체로 초기화
 
-(id)initWithObject : (NSArray*) objects forKeys:(NSArray*)keys;
현재 객체에 objects 배열을 내용으로 하고, keys 배열을 key로 해서 초기화.( 갯수가 같아야 함)
 
-(id)initWithObjectsAndKeys:(id)firstObject, ...;
현재 객체에 요소 추가 (값과 키를 쌍을 이루게 짝수로 인자를 넣고 nil로 마무리)
 
-(BOOL)isEqualsToDictionary:(NSDictionary*)other;
현재 객체와 other 객체가 동일한 지 리턴
 
-(NSArray*)allKeys;
현재 객체의 모든 요소의 Key를 NSArray 형으로 리턴
 
-(NSArray*)allValues;
현재 객제츼 모든 요소의 value를 NSArray형으로 리턴
 
-(unsigned)count;
현재 객체의 요소 개수 리턴
 
-(NSEnumerator*)keyEnumerator;
현재 객체의 key를 NSEnumerator형으로 리턴 (key를 통해서 value에 접근할 수 있으므로 피요한 method)
 
-(id)objectForKey:(id)aKey;
현재 객체의 aKey에 맞는 요소 리턴
 
 
NSMutableDictionary
Dictionary 객체를 변환 할 수 있는 기능을 가진 클래스
 
method
 
-(id)initWithCapacity : (unsigned)numItems;
 
+(id) dictionaryWithCapacity : (unsigned)numItems;
numItems 갯수 만큼 초기화
 
-(void) addEntriesFromDictionary:(NSDicionary*)otherDictionary;
otherDictionary 객체를 현재 객체에 추가
 
-(void)removeAllObject;
현재 객체의 모든 요소 삭제
 
-(void)removeObjectForKey:(id)aKey;
현재 객체에서 aKey를 가진 요소 삭제
 
-(void)removeObjectsForKeys:(NSArray*)keyArray;
현재 객체에서 keyArray의 Key요소를 삭제
 
-(void)setObject:(id)anObjectForKey:(id)aKey;
현재 객체 요소를 다른 anObject로 대체
 
-(void)setDictionary:(NSDictionary*)otherDictionary;
현재 객체를 다른 otherDictionary로 대체
 
 
 

'개발 > App Developer' 카테고리의 다른 글

XCode info.plist 아이폰,아이팟터치 주요항목 정리  (0) 2010.09.01
SQLite  (0) 2010.09.01
gdb 디버거  (0) 2010.09.01
Disclosure indicator , detail Disclosure Button  (0) 2010.09.01
  (0) 2010.09.01