取代存儲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