2014-05-18 2 views
2

plist에서 데이터를 먼저 검색하고, 데이터를 추가하고, plist 파일에 전체 내용을 다시 써야한다는 것을 알고 있습니다.xcode로 plist 할 데이터 저장

내 코드는 여기에 추가되지 않지만이 메소드를 호출 할 때마다 새로 고침됩니다.

- (void) saveDataToPlist { 
    // Retrieve path and filename of the plist file 
    NSString *myColorsListFile = [self dataFilePath]; 

    NSMutableArray *innerArray1; 
    NSString *error; 

    UserGivenColorHexString = HexTextField.text; 
    NSMutableDictionary *rootObj = [NSMutableDictionary dictionaryWithCapacity:100]; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:myColorsListFile]) { 
     // File exists 
     rootObj = [[NSMutableDictionary alloc] initWithContentsOfFile:myColorsListFile]; 


     [innerArray1 addObjectsFromArray:[NSMutableArray arrayWithContentsOfFile:myColorsListFile]]; 
     [innerArray1 addObject:UserGivenColorName]; 

    } else { 
     // Create file 
     rootObj = [[NSMutableDictionary alloc] init]; 

     innerArray1 = [NSMutableArray arrayWithObjects: UserGivenColorName, nil]; 
     [rootObj setObject:innerArray1 forKey:@"ColorName"]; 
    } 

    id plist = [NSPropertyListSerialization dataFromPropertyList:(id)rootObj format:NSPropertyListXMLFormat_v1_0 errorDescription:&error]; 

    [plist writeToFile:myColorsListFile atomically:YES]; 
} 

답변

3

는 문제의 무리가 될 것 같다 : 키에 문제가 시도가 수포이 될 것입니다 그것에 추가 할 수 있도록 PLIST가 발견 된 경우 당신이 innerArray1 변수를 설정하지 않는 것입니다.

innerArray1 = [rootObj objectForKey:@"ColorName"]; 

그런 다음 코드가 작동합니다 다음 PLIST의 내용 rootObj를로드 한 후에는 키 ColorName에있는 배열에 대한 참조를 취득 할 수 있습니다. 이 즉각적인 ISSE 관계가없는

, 거기에 몇 가지 다른 사소한 문제입니다

  • 당신은 myColorsListFile PLIST와 사전을 읽고,하지만 당신은 또한 innerArray1에 배열로이 내용을 추가하려고 . myColorsListFile의 후자의 사용은이 plist의 잘못된 사용으로 나를 공격합니다. 그 줄은 없앨거야.

  • UserGivenColorHexString을 설정 한 다음 UserGivenColorName을 저장 한 것으로 보입니다. 다른 곳에서 의도하지 않은 결과가 발생하지 않도록이 설정을 로컬 변수로 변경할 수도 있습니다. 두 변수 모두에 대해 동일한 변수를 사용하려고했다고 가정합니다.

  • 또한 나중에 삭제할 변경 가능한 사전을 인스턴스화하고 있습니다.

  • Cocoa Naming Conventions (소문자로 시작 변수)을 따르도록 제안 할 수 있습니다. 나는 또한 hexTextField이 정말로 재산이라고 추정했다.

  • "ColorName 배열을 찾았습니까?"논리에서 "파일 존재 여부"논리를 분리하는 것이 좀 더 강력 할 수 있습니다.

  • plist 생성 실패 오류가 발생 했으므로 로그에 기록 할 수 있습니다.

  • documentationdataFromPropertyList 지금은 사용되지 않는 것을 우리에게 알려줍니다

    특별 고려 사항

    이 방법은 무효이며, 곧 더 이상 사용되지 않습니다. 대신 dataWithPropertyList:format:options:error:을 사용하십시오.

그래서, 당신은 같은 끝낼 수 있습니다

- (void) saveDataToPlist { 
    // Retrieve path and filename of the plist file 
    NSString *myColorsListFile = [self dataFilePath]; 

    NSMutableArray *innerArray1; 
    NSError *error; 

    NSString *userGivenColorHexString = HexTextField.text; 
    NSMutableDictionary *rootObj; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:myColorsListFile]) { 
     rootObj = [[NSMutableDictionary alloc] initWithContentsOfFile:myColorsListFile]; 
    } else { 
     rootObj = [[NSMutableDictionary alloc] init]; 
    } 

    innerArray1 = [rootObj objectForKey:@"ColorName"]; 

    if (innerArray1) { 
     [innerArray1 addObject:userGivenColorHexString]; 
    } else { 
     innerArray1 = [NSMutableArray arrayWithObjects: userGivenColorHexString, nil]; 
     [rootObj setObject:innerArray1 forKey:@"ColorName"]; 
    } 

    id plist = [NSPropertyListSerialization dataWithPropertyList:(id)rootObj format:NSPropertyListXMLFormat_v1_0 options:0 error:&error]; 
    if (!plist) { 
     NSLog(@"dataFromPropertyList error: %@", error); 
    } 

    [plist writeToFile:myColorsListFile atomically:YES]; 
} 
+0

롭, 나는 귀하의 게시물/솔루션 UP 투표를 할 수있는 충분한 명성을 필요가 없습니다. 그러나 만약 내가 할 수 있다면 100 배나 더 많이했을 것입니다. 귀하의 솔루션은 완벽하게 작동하며 모든 의견은 높이 평가됩니다. 감사! – user3477156