2012-10-04 66 views
0

我來過這的代碼所示below.In下面的代碼,我能夠拯救只有一個單一的註釋,但是我有註解的數組,我能不能將它們保存與NSUserDefaults的單保存多個註釋-NSUserDefaults

To save: 

    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; 
    [ud setDouble:location.latitude forKey:@"savedCoordinate-latitude"]; 
    [ud setDouble:location.longitude forKey:@"savedCoordinate-longitude"]; 
    [ud setBool:YES forKey:@"savedCoordinate-exists"]; 
    [ud synchronize]; 

編輯:

-(void)viewDidLoad 
     NSUserDefaults *ud=[NSUserDefaults standardUserDefaults]; 
      if([ud boolForKey:@"save-exist"]) 
      { NSMutableArray *udAnnotations=[[NSMutableArray alloc]initWithArray: 
[ud objectForKey:@"annotationsArray"]]; 
       NSLog(@"%d",[udAnnotations count]); 
      } 
      else{ 
      [self addAnno]; 
      } 

    -(void)addAnno 
    { 

    [mapView addAnnotations:annotationArray]; 
    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults]; 
    [ud setObject:annotationArray forKey:@"annotationsArray"]; 
    [ud setBool:YES forKey:@"save-exist"]; 
    [ud synchronize]; 

} 

回答

1

正如你已經有一個數組,只需使用setObject:forKey:arrayForKey:

由於鄰你原來的數組中bjects是不是可以直接保存,其數據存儲在字典類型:

NSMutableArray *saveData = [[NSMutableArray alloc] initWithCapacity:originalData.count]; 
for(id location in originalData) { 
    [saveData addObject:@{@"lat":[location latitude], @"lon":[location longitude]}]; 
} 
[[NSUserDefaults standardUserDefaults] setObject:saveData forKey:@"annotationsArray"]; 

和轉換上檢索:

NSMutableArray *restoredData = [[NSMutableArray alloc] init]; 
for(NSDictionary *data in [[NSUserDefaults standardUserDefaults] arrayForKey:@"annotationsArray"]) { 
    [restoredData addObject:[[Location alloc] initWithLat:data[@"lat"] andLon:data[@"lon"]]]; 
} 
// if restoredData.count is 0, there were no stored objects. 

一對夫婦的注意事項:

  • 如果您不使用ARC,請記住釋放alloc'd對象。
  • 這使用了新的目標對象c文字語法和字典訪問語法。如果你不使用的Xcode 4.5,你需要構建和訪問他們的傳統方式,dictionaryWithObjectsAndKeys:objectForKey:
+0

您好凱文,我真的很感謝你的回答。我剛剛實現了你描述的方式,但它不會讓我回到我的可變數組。我剛剛在編輯的部分下張貼了我的原始代碼。我不知道爲什麼當我收回我的數組時,我正在獲取O對象!任何想法? – casillas

+1

根據[該文檔(https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/occ/instm/NSUserDefaults/的setObject:forKey :),數組的元素必須是屬性列表對象,所以你可能將它們轉換爲,例如,存儲之前詞典,朗讀起來時轉換回。 – Kevin

+0

非常感謝凱文。你知道任何文件,我怎麼可以將NSMutableArray轉換爲字典? – casillas