取代存储BOOL
,您可以存储上次随机播放的日期/时间(NSDate
)。
然后通过比较存储日期和viewDidAppear
中的当前日期,检查自上次洗牌后是否已经过午夜。
见NSTime
文档:http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
而且NSDateFormatter
文档: https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003643
UPDATE:
按照要求,这里是一些示例代码。无可否认,这可能是更好的解决方案,但我相信这段代码会帮助你解决问题。这样做是检查是否有使用NSUserDefaults
保存的日期,然后与当前日期进行比较。如果日期不匹配,请将数组随机播放,然后保存当前日期(再次使用NSUserDefaults
)。 (我已经采取做的假设,确实时间会继续前进的自由,所以它不检查,以确保lastSavedDate
是以前的currentDate
)
NSDate *currentDate = [[NSDate alloc] init];
NSDate *lastShuffleDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastShuffleDate"];
// check to see if there is a prior shuffle date
// if there is not, shuffle the array and save the current date
if (!lastShuffleDate) {
NSLog(@"No object set for 'lastShuffleDate'");
//[self shuffleMyArray];
[[NSUserDefaults standardUserDefaults] setObject:currentDate forKey:@"lastShuffleDate"];
return;
}
// set up the date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSLog(@"Current Date: %@", [dateFormatter stringFromDate:currentDate]);
NSLog(@"Saved Date: %@", [dateFormatter stringFromDate:lastShuffleDate]);
// check to see if the dates are the same by comparing the dates as a string
if (![[dateFormatter stringFromDate:currentDate] isEqualToString:[dateFormatter stringFromDate:lastShuffleDate]]) {
NSLog(@"Dates are different...!");
//[self shuffleMyArray];
} else {
NSLog(@"Dates are the same... (midnight has not passed)");
}
// save the time of the last shuffle
[[NSUserDefaults standardUserDefaults] setObject:currentDate forKey:@"lastShuffleDate"];
在这一点上,你没有真正的理由来检查时间,但我已经包括它,以防万一你好奇。
// remote dateStyle and set timeStyle to check times
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSLog(@"Current Time: %@", [dateFormatter stringFromDate:currentDate]);
NSLog(@"Saved Time: %@", [dateFormatter stringFromDate:lastShuffleDate]);
来源
2013-03-19 19:22:52
rog
这将是一种方式,但你也需要保存你正在“洗牌”并加载这些项目的状态。 – 2013-03-19 18:49:45
数组对象来自CoreData,因此它们已经被保存。该方法只是将它们加载到一个数组中,并将它们混洗到另一个数组中。 – RoshDamunki 2013-03-19 19:35:30