2011년 6월 17일 금요일

.plist(property list) 데이터 입력과 읽기

Xcode 프로젝트에 .plist 파일을 추가한다. 
예제에서는 “data.plist”를 사용


다음으로 문서디렉토리에 .plist 경로를 생성한다.


NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3

NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”]; //5

[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
1) 경로의 리스트를 생성
2) 리스트로부터 문서 경로를 가져온다.
3) 전체 경로를 생성.
4) 파일이 존재하는 지 체크.
5) 번들 디렉토리에 만들었던 문서의 경로를 가져온다.
6) document directory에 번들 파일 경로를 복사한다.
데이터 읽기:
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

//load from savedStock example int value
int value;
value = [[savedStock objectForKey:@"value"] intValue];
[savedStock release];

데이터 쓰기:


NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//here add elements to data file and write data to file
int value = 5;
[data setObject:[NSNumber numberWithInt:value] forKey:@”value”];

[data writeToFile: path atomically:YES];
[data release]
두가지를 기억:

1)  Xcode project 에 문서를 생성.
2) 앱을 최적화하기 위해서는 app종료 혹은 뷰 종료시 모든 데이터를 저장한다. applicationWillTerminate 인스턴스에 추가. 대용량 데이터라면 이 방법은 사용하지 않는게 좋다. 앱 종료시 오래 걸리고 종종 강제 종료가 발생한다.


iphone simulator document 경로 _ 사용자 -> 라이브러리 -> application Support -> iPhone Simulator -> iOS버전 -> Applications - > 앱의 일련번호 

댓글 없음:

댓글 쓰기