2009-11-08 7 views
3

각 항목이 사전 인 기본 사전이 있습니다. 이것을 plist에 저장하고 나중에 내용을 검색해야합니다. IPHONE : plist에서 사전 사전 저장 및 검색

내가

// create a dictionary to store a fruit's characteristics 
NSMutableDictionary *fruit = [[NSMutableDictionary alloc] init]; 
[fruit setObject:quantity forKey:@"quantity"]; 
[fruit setObject:productID forKey:@"productID"]; 
[fruit setObject:nameID forKey:@"nameID"]; 

// create a dictionary to store all fruits 
NSMutableDictionary *stock = [[NSMutableDictionary alloc] init]; 
[stock setObject:fruit forKey:@"nameID"]; 

... 주식 사전에 모든 과일을 추가 한 후하는 PLIST

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"stock.plist"]; 

NSMutableDictionary *stock = [NSMutableDictionary dictionaryWithContentsOfFile:path]; 
[stock writeToFile:path atomically:YES]; 

에 주식을 쓰기에 사전을 저장하고있는 무슨이다 사전을 복원, 나는 사용

NSMutableDictionary *stock = [NSMutableDictionary dictionaryWithContentsOfFile:path]; 

... 그러나 이것은 파일에 아무것도 저장하지 않습니다 ... 내가 뭘 놓치고 있습니까?

도움을 주셔서 감사합니다.

답변

10

당신은 쓰기 :

... 재고 사전에 모든 과일을 추가 한 후하는 PLIST에 주식을 쓰기

하지만 재고 사전을 디스크에 기록하기 전에 디스크에서 코드를 읽는 중입니다. Stock.plist가 실제로 그 경로에 존재하지 않는다는 가정하에 주식을 nil로 설정 했으므로 writeToFilePath 메시지를 nil로 보냈습니다. 마지막으로

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"stock.plist"]; 
// write plist to disk 
[stock writeToFile:path atomically:YES]; 

// read it back in with different dictionary variable 
NSMutableDictionary *savedStock = [NSMutableDictionary dictionaryWithContentsOfFile:path]; 
if(savedStock==nil){ 
    NSLog(@"failed to retrieve dictionary from disk"); 
} 

, 수량 및 제품 일련 어떤 데이터 유형 :

이 시도? 당신은 비 객체 데이터 유형을 직렬화 할 수 없기 때문에 수량이 정수의 경우, 그렇게처럼 포장해야합니다 :

[fruit setObject:[NSNumber numberWithInt:quantity] forKey:@"quantity"]; 

property list serialization을 읽는 시간을 보내십시오.

+0

감사합니다. 이 줄 [주식 writeToFile : 경로 atomically : 예]; 사전을 사전 순으로 직렬화하여 파일에 저장 하시겠습니까? dictionaryWithContentsOfFile이 동일한 구조를 다시 읽습니까? – SpaceDog

5

dictionaryWithContentsOfFile 저장하지 않고 파일을 읽습니다. 파일에 쓰는 코드가 보이지 않습니다.

당신은 당신의 저장 코드에서 이런 식으로 뭔가를 필요로하기 위하여려고하고있다 : 당신은 (재) 파일의 내용 stock를 만드는

[stock writeToFile:path atomically:YES]; 
1

을 즉시 쓰기 전에. 파일이 존재하지 않으므로 사전은 nil입니다. 그것을 쓰려고하면 아무 것도 생산하지 않습니다. 대신 이미 채워진 stock 버전을 사용해야합니다.

(구원의 비트가 같은 범위에있는 가정, 단지 writeToFile에 대한 호출 위 NSMutableDictionary *stock를 시작하는 줄을 삭제합니다.)

는 (비록 그것을 생각해 보면, 그것은 동일한 범위에있을 수 없습니다 . 나 컴파일러가 처음부터 불평 것)