2009-12-12 9 views
3

를 업데이트하는 방법 내가 NSUserDefaults에 값을 업데이트해야합니다 다음과 같은 코드가 있습니다NSUserDefault

- (id) createBoardWithTitle:(NSString *)pTitle withScores:(NSArray *)pScores andNames:(NSArray *)pNames andDisplayStrings:(NSArray *)pStrings orderBy:(NSString *)pOrder ofType:(NSString *)pType 
{ 

    if((self == [super init])) 
    { 

     boardEntries = [NSMutableArray arrayWithCapacity:10]; 

     // Build the data 

      for(...){ 
       // populate boardEntries 
      } 


     // create an Dictionary to save 
     NSDictionary *savedData = [NSDictionary dictionaryWithObjectsAndKeys:pType, @"type", pOrder, @"order", boardEntries, @"entries", nil]; 

      // Load the old boards 
     NSDictionary *existingBoards = [[NSUserDefaults standardUserDefaults] objectForKey:@"BlockDepotLeaderboards"]; 

      // Create a mutable dictionary to replace the old immutable dictionary 
     NSMutableDictionary *newBoards = [NSMutableDictionary dictionaryWithCapacity:[existingBoards count]+1]; 

      // transfer the old dictionary into the new dictionary 
     [newBoards addEntriesFromDictionary:existingBoards]; 

      // add the new board to the new dictionary 
     [newBoards setObject:savedData forKey:pTitle]; 

      // check to make sure it looks like it should by eye 
     NSLog(@"New Boards: %@", newBoards); 

      // Replace the old date in NSUserdefaults 
     [[NSUserDefaults standardUserDefaults] setObject:newBoards forKey:@"BlockDepotleaderboards"]; 
      // Update: Do I really need to call this? 
     [[NSUserDefaults standardUserDefaults] synchronize]; 

      // Check to make sure it looks as it should by eye 
     NSLog(@" Defaults--- %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"BlockDepotLeaderboards"]); 
    } 

    return self; 

} 

는 지금까지 내가 말할 수있는, 즉, 관련 코드의를. 그것은 아마 그것이 필요로하는 것보다 "더 어색하다". 하지만 NSUserDefaults에서 반환 된 모든 내용은 변경되지 않으므로 Mutable 개체로 다시 만들어야하고 NSUserDefaults에서 개체를 추가해야하는 항목을 추가해야합니다. 그리고 저는 위에서 시도한 것이 효과가 있다고 생각합니다.

(@ "새 보드 %의 @", newBoards) NSLog의 출력 ID가

New Boards: { 
    "Marathon: Times" =  { 
     entries =   (
         { 
       displayString = "10:00"; 
       name = "Tom Elders"; 
       score = 600; 
      }, 
         { 
       displayString = "10:30"; 
       name = "A.R. Elders"; 
       score = 630; 
      }, 
         { 
       displayString = "11:00"; 
       name = "L. Lancaster-Harm"; 
       score = 660; 
      }, 

      // and so on..... 

     ); 
     order = ASC; 
     type = TIMES; 
    }; 
    String = Test; 
} 

"문자열 = 검사가"단지 시험 항목이며,이 같은 AppDelegate.m 파일에 설정됩니다 :

if(![[NSUserDefaults standardUserDefaults] objectForKey:@"BlockDepotLeaderboards"]){ 

    NSMutableDictionary *leadboardHolder = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Test", @"String", nil];  
    [[NSUserDefaults standardUserDefaults] setObject:leadboardHolder forKey:@"BlockDepotLeaderboards"]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 



}else{ 
    NSLog(@"Leaderboards Dict Exists %@", [NSUserDefaults standardUserDefaults]); 
} 

그래서 나는 내가 가진 것이 분명히 있음을 안다. 나는 이것이 내가 어리 석고 어리 석다는 것을 알게된다. 그러나 나는 그것을 볼 수 없거나 그것을 이해할 수 없다.

나는 엉망진창을 볼 수 있습니까? 워드 프로세서에 따르면

+0

'objectForKey : @ "BlockDepotLeaderboards"를하지 마십시오. 반환 된 객체가 실제로 무엇인지 전혀 알 수 없습니다. 대신 -dictionaryForKey :를 사용하고 새로운 사전을 작성하여 nil 인 경우를 처리하십시오. –

+0

NSUserDefaults에서 값에 액세스하는 경우 dictionForKey :를 사용하거나 사전에 객체를 캐스팅해야합니다 –

답변

5

보고, 저것은 관련 코드입니다. 그것은 아마 그것이 필요로하는 것보다 "더 어색하다". 하지만 NSUserDefaults에서 반환 된 모든 내용은 변경되지 않으므로 Mutable 개체로 다시 만들어야하고 NSUserDefaults에서 개체를 추가해야하는 항목을 추가해야합니다.

쉬운 방법은 다음과 같이 불변 사전의 mutableCopy를 만드는 것입니다 :

NSMutableDictionary *newBoards = [[immutableDict mutableCopy] autorelease]; 
[newBoards setObject:savedData forKey:pTitle]; 

는 또한, synchronize 디스크에 사용자의 기본 설정을 저장 강제하는 데 사용됩니다. 파인더에서 plist를 열 때 볼 수있는 것만 영향을줍니다. 응용 프로그램의 관점에서 NSUserDefaults 항상 최신입니다. 또한 기본값은 잠시마다 자동으로 저장되므로 synchronize 번으로 전화해야하는 유일한 시간은 응용 프로그램이 종료되는 시간입니다.

0

: 기본 개체 속성 목록이어야합니다

, 즉, 인스턴스 (또는 컬렉션 인스턴스 의 조합)을 NSData,있는 NSString,의 NSNumber, NSDate, NSArray 또는 NSDictionary입니다.

serialize하려는 모든 개체에 대한 확신이 있습니까? NSKeyedArchiver

를 살펴 보자 또한 지금까지 내가 말할 수있는이 질문에 Why NSUserDefaults failed to save NSMutableDictionary in iPhone SDK?

+0

NSKeyedArchiver를 다른 용도로 사용하고 있습니다. 이 프로젝트는 주로 자기 가르치기 프로젝트이므로 나는 이걸 찍고 싶습니다. 그러나 나는 똑같은 생각을하고있었습니다. 내가 말할 수있는 한, 두 개의 NSString과 NSArray를 포함하는 NSArray를 포함하는 NSArray를 포함하는 NSArray와 NSDictionary를 저장하려고합니다. 그러나 나는 돌아가서 그것을 점검한다. – gargantuan

0

첫째 아무것도 저장시 :

[[NSUserDefaults standardUserDefaults] setObject:@"Previous Value" forKey:@"Name"]; 

그런 다음 같은 키의 값을 업데이트 다시이 코드를 실행 :

[[NSUserDefaults standardUserDefaults] setObject:@"Updated Value" forKey:@"Name"]; 

당신이 [[NSUserDefaults standardUserDefaults] 동기화 호출 할 필요가없는 ] 때문에 성능 문제가 있습니다. 단지 필요한 것입니다. iOS 은 잘 관리합니다.

개체를 제거 할 필요가 없습니다. 같은 키를 업데이트하십시오. 특정 키의 값을 업데이트합니다. 희망이 도움이됩니다.

관련 문제