2012-09-16 4 views
2

질문은 이전에 많은 질문과 유사하게 보일 수 있지만 모든 질문과 대답을 읽은 후에 무엇을해야하는지 이해할 수 없었습니다..plist에 데이터를 쓰십시오.

wordNameswordDefinitions 및 일부 IDdate ID을 가진 여러 단어를 쓰고 싶습니다. 다음 코드가 있지만 다른 데이터 형식을 사용하는 배열을 사용하는 사전에 대한 두 가지 질문과 사전에 대한 키 정의 방법이 있습니다.

내가 만드는 모든 .plist 파일이 잘못되어 있으면 나를 수정하십시오.

미리 감사드립니다.

- (IBAction)addWord:(id)sender 
{ 
NSString *destinationPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
destinationPath = [destinationPath stringByAppendingPathComponent:@"Box.plist"]; 

NSFileManager *fileManager = [NSFileManager defaultManager]; 

if (![fileManager fileExistsAtPath:destinationPath]) 
{ 
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"Box" ofType:@"plist"]; 
    [fileManager copyItemAtPath:sourcePath toPath:destinationPath error:nil]; 
} 

// Load the Property List. 
NSMutableArray* wordsInTheBox = [[NSMutableArray alloc] initWithContentsOfFile:destinationPath]; 


NSString *wordName = word.name; 
NSString *wordDefinition = word.definition; 
NSInteger deckID; 
NSDate addedDate; 


//is this correct to have an array of different types? 
NSArray *values = [[NSArray alloc] initWithObjects:wordName, wordDefinition, deckID, addedDate, nil]; 
//How and where am I supposed to define these keys? 
NSArray *keys = [[NSArray alloc] initWithObjects: NAME_KEY, DEFINITION_KEY, DECK_ID_KEY, DATE_KEY, nil]; 
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:values forKeys:keys]; 
[wordsInTheBox addObject:dict]; 
[wordsInTheBox writeToFile:destinationPath atomically:YES]; 
} 

답변

3

initWithContentsOfFile: 항상 불변의 배열을 반환합니다. 당신은이에해야 다음 word 변수가 정의되는 경우 내가 완전히 이해하지 못하는 것은

NSMutableArray *wordsInTheBox = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithContentsOfFile:destinationPath]]; 

. 그것은 ivar입니까?

Xcode (4.4 또는 4.5)의 최신 버전을 사용하는 경우 사전을 만드는 데 훨씬 간단한 리터럴을 사용하는 것이 좋습니다.

NSDictionary *dict = @{NAME_KEY  : wordName, 
         DEFINITION_KEY : wordDefinition, 
         DECK_ID_KEY : deckID, 
         DATE_KEY  : addedDate}; 

하지만 사전 정의에도 문제가 없습니다. 그것은 작동해야합니다.

NAME_KEY, DEFINITION_KEY 등이 어딘지 정의되어 있는지 확인해야합니다. 모든 모자는 보통 전처리 매크로에 사용되는, 그래서 당신은 같은 것을 할 수있는 :

NSDictionary *dict = @{@"Name"  : wordName, 
         @"Definition" : wordDefinition, 
         @"DeckID"  : deckID, 
         @"Date"  : addedDate}; 

을하지만 매크로를 사용하는 것이되지 않습니다 :

#define NAME_KEY @"Name" 
#define DEFINITION_KEY @"Definition" 

또한 단순히 사전에 직접 문자열을 사용할 수를 나쁜 아이디어.

+0

자세한 답변을 주셔서 감사합니다. 그 특성과 물건과 별도의 클래스에 Word 개체가 있습니다. 나는 당신이 곧 언급 한 것을 시도 할 것이고 그것에 대해 알려줄 것입니다. 오후 8시 30 분 P.S. Xcode 4.2.1을 사용하고 있습니다. – Neeku

관련 문제