我試圖將位置數組保存到NSUserDefaults。首先,我將CLLocationCoordinates轉換爲一個NSValues數組,並使用NSUserDefaults進行保存。 這是到目前爲止我的代碼:將NSMutable陣列保存到NSUserDefaults時出錯
_locationsArray = [[NSMutableArray alloc] init];
NSUInteger count = [self.locations count];
CLLocationCoordinate2D coordinates[count];
for (NSInteger i = 0; i < count; i++) {
coordinates[i] = [(CLLocation *)self.locations[i] coordinate];
NSValue *locationValue = [NSValue valueWithMKCoordinate:coordinates[i]];
[_locationsArray addObject:locationValue];
}
NSLog(@"location = %@", _locationsArray);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:totalDistance forKey:@"totalDistance"];
[defaults setObject:_locationsArray forKey:@"mapOverlay"];
// [defaults setDouble:_totalTime forKey:@"totalTime"];
[defaults setObject:avgSpeedToBeSaved forKey:@"averageSpeed"];
[defaults setObject:totalCalories forKey:@"totalCalories"];
[defaults synchronize];
不過,我得到以下錯誤:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSUserDefaults setObject:forKey:]: attempt to insert non-property list object (
"<8b4df1d9 36ab4240 d5059bbe 47825ec0>",
"<f6dd639f 36ab4240 a2a7b7f5 49825ec0>",
"<f6dd639f 36ab4240 a2a7b7f5 49825ec0>",
"<20c46379 36ab4240 5ff02732 4c825ec0>",
"<20c46379 36ab4240 5ff02732 4c825ec0>",
"<d24c9c81 36ab4240 2bd75f9f 4e825ec0>",
"<d24c9c81 36ab4240 2bd75f9f 4e825ec0>",
"<d810b96c 36ab4240 f4d96401 51825ec0>",
"<d810b96c 36ab4240 f4d96401 51825ec0>"
) for key mapOverlay'
我想,如果我轉換的座標NSValues會被罰款保存到NSUserDefaults的 - 是那不是這種情況?我應該怎麼做呢?
閱讀'NSUserDefaults'的文檔。 'NSValue'不是支持的數據類型之一。 – rmaddy
相關:[爲什麼NSUserDefaults無法在iPhone SDK中保存NSMutableDictionary?](http://stackoverflow.com/questions/471830/why-nsuserdefaults-failed-to-save-nsmutabledictionary-in-iphone-sdk/471920#471920) –
只是想提一個可能更簡單的替代方法:而不是NSValues,嘗試定義一個自定義類X,該類將座標保存爲NSNumber屬性。然後將X的實例添加到數組中。另一種選擇是包含座標爲NSNumbers的字典數組。 – Anna