我有它實現NSCoding的自定義對象,它看起來像這樣(簡化當然):節能字典NSCoding反對NSUserDefaults的
@implementation FooBarThing
@synthesize foo = _foo;
@synthesize bar = _bar;
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
_foo = [[coder decodeObjectForKey:FOO] retain];
_bar = [[coder decodeObjectForKey:BAR] retain];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.foo forKey:FOO];
[coder encodeObject:self.bar forKey:BAR];
}
@end
目前,我在我的自定義類的數組保存到NSUserDefaults的,像這樣:
-(void)saveResults:(NSArray *)results
{
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:results];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"RESULTS"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(NSArray*)readResults
{
NSData *results = [[NSUserDefaults standardUserDefaults] objectForKey:@"RESULTS"];
NSArray *resultsArray = [NSKeyedUnarchiver unarchiveObjectWithData:results];
return resultsArray;
}
我想要做的,是結果的陣列存儲在一個字典,用繩子像這樣鍵入:
-(void)saveResults:(NSArray *)scanResults forKey:(NSString *)key
{
???
}
-(NSArray*)readResults:(NSString *) key
{
???
}
讓我的語法正確無誤,我開始相信我只是在想這個,所以幫助將apprecaited! 謝謝!
-
編輯:
因爲我已經解決了這個,這是很簡單的只是有一個瞬間失效。也許不是最好的選擇,所以打開任何改善建議!
-(void)saveResults:(NSArray *)results forKey:(NSString *)key
{
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithDictionary:[self getResultsDict]];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:results];
if(dict == nil){
dict = [NSMutableDictionary dictionaryWithObject:data forKey:key];
}else{
[dict setObject:data forKey:key];
}
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:dict forKey:@"RESULTS_DICT"];
[userDefaults synchronize];
}
-(NSArray*)readFullResults:(NSString *)key
{
NSDictionary *dict = [self getResultsDict];
NSArray *result = nil;
if(dict != nil){
[dict objectForKey:key];
NSData *data = [dict objectForKey:key];;
result = [NSKeyedUnarchiver unarchiveObjectWithData: data];
}
return result;
}
-(NSArray*) getDates
{
NSDictionary *dict = [self getResultsDict];
if(dict != nil)
{
return [dict allKeys];
}
return nil;
}
- (NSDictionary*)getResultsDict{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *resultsDict = [userDefaults objectForKey:@"RESULTS_DICT"];
return resultsDict;
}
是否要將結果存儲在字典或默認系統中?你想在saveResults中做什麼:forKey:? – Caleb
我正在尋找將結果保存在字典中,並將字典置於系統默認值中。自從我編輯了我的答案以包含我的解決方案。謝謝您的幫助。 – xceph
真的應該從問題中刪除答案,並將答案標記爲已接受的答案。 – Caleb