我想在NSUserDefaults中保存一個對象,但是我沒有成功。情景是,我有SyncObjct類的對象syncObject。我在SyncObject類中實現了以下方法在NSUserDefaults中存儲自定義對象
- (NSMutableDictionary*)toDictionary;
+ (SyncObject*)getFromDictionary :(NSMutableDictionary*)dictionary;
- (id) initWithCoder: (NSCoder *)coder;
- (void) encodeWithCoder: (NSCoder *)coder;
而且SyncObject類是NSCoding類。現在,SyncObject類包含一個名爲jobsArray的NSMutableArray。該數組包含類JobsObject的對象。我爲這個類實現了上述相同的方法,以使它符合編碼。在SyncObject類的toDictionary方法中,我通過編寫以下行將此數組存儲在字典中。
[dictionary setValue:jobsArray forKey:@"jobsArray"];
我正在通過編寫以下行在SyncOject類的getFromDictionary方法中檢索它。
+ (SyncObject*)getFromDictionary :(NSMutableDictionary*)dictionary
{
NSLog(@"SyncObject:getFromDictionary");
SyncObject *syncObject = [[SyncObject alloc] init];
@try
{
syncObject.noOfJobs = [[dictionary valueForKey:@"noOfJobs"] intValue];
syncObject.totalJobsPerformed = (TotalJobsPerformed*)[dictionary valueForKey:@"totalobsPerformed"];
syncObject.jobsArray = [dictionary valueForKey:@"jobsArray"];
}
@catch (NSException * e)
{
NSLog(@"EXCEPTION %@: %@", [e name], [e reason]);
}
@finally
{
}
return syncObject;
}
而且我還通過編寫以下行在NSUserDefault中存儲syncObject。
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:syncObject];
[userStorage setObject:myEncodedObject forKey:SYNC_OBJECT];
我NSUserDefaults的從通過編寫以下行
NSData *myEncodedObject = [userStorage objectForKey: SYNC_OBJECT];
syncObject = (SyncObject*)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];
問題檢索對象是我不能夠正確地檢索jobsArray。一些無效的對象返回並且在嘗試訪問應用程序時崩潰。請誰能告訴我這個問題的原因?
問候
您使用的線程?你叫NSUserDefault的同步嗎? – daveoncode