2014-06-18 7 views
1

내 앱에 맞춤 plist가 있습니다. 중첩 된 레벨에 새 키를 추가하고 싶습니다.중첩 된 plist에 새 키를 추가하는 방법

어떻게 추가 할 수 있습니까? 프로그래밍 방식으로?

다음은 내 plist 파일의 구조입니다. : 어떻게 구현합니까?

미리 감사드립니다.

+0

'+'버튼을 누르시겠습니까? – trojanfoe

+0

현재 문제는 무엇입니까? 왜 그것을 추가 할 수 없습니까? 언급 한대로 @trojanfoe로 파일을 편집 하시겠습니까? 아니면 코드 전체에서 프로그래밍 방식으로 수행하고 싶습니까? – Neeku

+0

프로그래밍 방식으로 추가하겠습니다. – Krunal

답변

2

App-Bundle의 파일을 편집 할 수 없습니다. NSMutableDictionary으로 읽어야하며 변경하고 문서 폴더에 저장하십시오.

/*--- get bundle file  ---*/ 
NSString *path = [[NSBundle mainBundle] pathForResource:@"Products" ofType:@"plist"]; 
NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; 

/*--- set value with key ---*/ 
[rootDict setValue:@"NewKeyContent" forKeyPath:@"Mobiles.Brands.TheNewKey"]; 

/*--- get documents path ---*/ 
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES) lastObject]; 
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Products.plist"]; 

/*--- save file   ---*/ 
[rootDict writeToFile:writablePath atomically: YES]; 

그 후에는 Documents 디렉토리에서 열어야합니다. 그렇지 않으면 항상 깨끗한 슬레이트로 시작하게됩니다.

/*--- get documents file ---*/ 
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES) lastObject]; 
NSString *path = [docPath stringByAppendingPathComponent:@"Products.plist"]; 
NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; 

/*--- set value with key ---*/ 
[rootDict setValue:@"NewKeyContent" forKeyPath:@"Mobiles.Brands.TheNewKey"]; 

/*--- get bundle file  ---*/ 
[rootDict writeToFile:writablePath atomically: YES]; 
+0

이 Mobiles.Brands.TheNewKey 키가 Mobiles 아래에 추가되었으며 Mobiles 아래에 추가되지 않았습니다. – Krunal

+0

죄송합니다. 그것의'setValue : forKeyPath :'. 나는 anser 코드를 수정했다. – nooitaf

+0

훌륭하게 작동하지만, 만약 그 키가 plist에 있는지 확인하고 싶습니다. 그게 무슨 구문을 사용해야합니까? – Krunal

0

사전을 만들려면 NSMutableDictionary + (id/* NSDictionary * * /) dictionaryWithContentsOfFile : (NSString *) 경로를 사용하십시오. 그리고 사용 [사전 setValue : @ "new_value"forKeyPath : @ "Mobiles.Brands.new_key"];

0

다른 사람들이 말한 것처럼 plist 편집기에서 "+"버튼을 클릭하면 새 키를 추가해야합니다.

코드에서 plist를 편집하려면 훨씬 더 복잡합니다.

plist 파일은 모든 개체가 불변으로 메모리에 읽혀집니다. 추가하려는 객체까지 전체 브랜치의 변경 가능한 복사본을 만들어야합니다. 이런 일 : 그것은 까다로운 비록 가능

//Make a mutable copy of the outermost dictionary 
NSMutableDictionary *outer = [startingOuterDict mutableCopy]; 

//Create a mutable copy of the dictionary at key "Mobiles" and replace it in "outer" 
NSMutableDictionary *mobiles = [outer[@"Mobiles"] mutableCopy]; 
outer[@"Mobiles"] = mobiles; 

//Create a mutable copy of the dictionary at key "Brands" and replace it in "mobiles" 
NSMutableDictionary *brands = [mobiles[@"Brands"] mutableCopy]; 
mobiles[@"Brands"] = brands; 

//Finally, add a new key in the "Brands" dictionary 
brands[@"newKey"] = @"Apple"; 

그들의 가변 당량, 사전, 배열, 세트 객체 그래프의 모든 컨테이너 변환 "mutableDeepCopy"쓰기 방법. 그러나이 경우에는 필요하지 않습니다.

관련 문제