答案 0 :(得分:2)
如何创建自定义类AllAlarms,它将在NSDictionary中保存每个警报,然后将其保存在一个密钥下的NSUserDefaults中。然后,您可以创建类方法,在需要时从NSUserDefauls返回所有警报的数组。这样您就可以搜索更快的数组。这是一个显示这个想法的代码摘录。它来自去年的CS193P。如果您想知道讨论的确切视频,请与我们联系。您必须确保存储在NSDictionary中的所有内容都是pLists。希望这会有所帮助。
@property (nonatomic, strong) NSString *start;
@property (nonatomic, strong) NSString *end;
-(id)init
{
//Do not call your setters and getters in the designated initializer function of a class. Use instance variable to set the value.
self = [super self];
if(self){
_start = [NSDate date]; // returns date now
_end = _start;
}
return self;
}
-(NSTimeInterval) duration
{
//To return the different between dates you can use timeIntervalSinceDate: method
return [self.end timeIntervalSinceDate:self.start];
}
//Writing out custom class to NSUserDefaults
#define START_KEY @"StartDate"
#define END_KEY @"EndDate"
#define SCORE_KEY @"Score"
#define ALL_RESULTS_KEY @"GameResult_All"
-(void)synchronize
{
NSMutableDictionary *mutableGameResults = [[[NSUserDefaults standardUserDefaults] dictionaryForKey:ALL_RESULTS_KEY]mutableCopy]; //get a mutable copy because NSUserDefaults are not mutable
if(!mutableGameResults) mutableGameResults = [[NSMutableDictionary alloc]init];
mutableGameResults[[self.start description]] = [self asPropertyList];
[[NSUserDefaults standardUserDefaults]setObject:mutableGameResults forKey:ALL_RESULTS_KEY];
[[NSUserDefaults standardUserDefaults] syncronize];
}
-(id)initFromPropertyList:(id)pList
{
//convenience initializer
self = [self init];
if(self){
if([pList isKindOfClass:[NSDictionary class]]){
NSDictionary *resultDictionary = (NSDictionary *)pList
_start = resultDictionary[START_KEY];
_end = resultDictionary[END_KEY];
_score = [resultDictionary[SCORE_KEY] intValue];
if(!_start || !_end) self = nil;
}
}
return self;
}
-(id)asPropertyList
{
//returns a dictionaryof all the properties
return @{START_KEY : self.start, END_KEY : self.end, SCORE_KEY : @(self.score)};
}
+(NSArray) allGameResults
{
// returns all game results that are stored in NSUserDefaults in an Array
NSMutableArray *allGameResults = [[NSMutableArray alloc]init];
for(id plist in [[[NSUserDefaults standardUserDefaults] dictionaryForKey:ALL_RESULTS_KEY] allValues]){
GameResult *result = [[GameResult alloc] initFromPropertyList:pList]; // using convenience initilazer to create game results from NSUserDefaults
[allGameResults addObject:result];
}
return allGameResults;
}