app delegate中的以下代码应该为分配数组每天一次添加新分配。问题是,每次打开应用程序时,即使日期没有改变,也会添加新的作业。每次打开应用程序时,似乎都会发布NSCalendarDayChanged。
var assignments = [Assignment]()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let _ = loadHW(){
assignments = loadHW()!
}
if let assignment = NSKeyedUnarchiver.unarchiveObject(withFile: Assignment.ArchiveURL.path) as? [Assignment]{
assignments = assignment
}
// Define identifier
let notificationName = Notification.Name("NSNotification.Name.NSCalendarDayChanged")
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(calendarDayDidChange(notification:)), name: notificationName, object: nil)
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
// Override point for customization after application launch.NSNotification.Name.NSCalendarDayChanged
return true
}
func calendarDayDidChange(notification : NSNotification)
{
let currentDate = Date()
let dateFormatter = DateFormatter()
let dayOfTheWeek = Calendar(identifier: Calendar.Identifier.gregorian).component(.weekday, from: Date())
print(dayOfTheWeek)
dateFormatter.dateFormat = "M/dd/YY"
let convertedCurrentDate = dateFormatter.string(from: currentDate)
print(convertedCurrentDate)
//Adds an assignment based on date comparisons
if let dates = NSKeyedUnarchiver.unarchiveObject(withFile: SettingsViewController.datesURL.path) as? [Date] {
print(1)
if currentDate >= dates[0] && currentDate <= dates[1] {
print(2)
if let weekendHW = NSKeyedUnarchiver.unarchiveObject(withFile: SettingsViewController.weekendURL.path) as? Bool {
print(3)
if(weekendHW || (!weekendHW && dayOfTheWeek != 1 && dayOfTheWeek != 7)){
print(4)
if assignments.count > 0{
assignments.insert(Assignment(hw: assignments[0].hw, date: convertedCurrentDate)!, at: 0)
print(5)
}else if assignments.count == 0 {
assignments.append(Assignment(hw: "", date: convertedCurrentDate)!)
print(6)
}
saveHW()
print("save complete")
}
}
}
}
//adds assignment on first launch of app
if assignments.count == 0 {
assignments.append(Assignment(hw: "", date: convertedCurrentDate)!)
saveHW()
}
}
func saveHW() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(assignments, toFile: Assignment.ArchiveURL.path) //saves array grades to file defined in Assignment class
if !isSuccessfulSave { //Diagnostic
print("Save failed")
}
}
func loadHW() -> [Assignment]? {
return NSKeyedUnarchiver.unarchiveObject(withFile: Assignment.ArchiveURL.path) as? [Assignment] //gets array grades from file where saved, defined in Assignment class
}
我可以更改为确保每天只创建一项作业?
答案 0 :(得分:0)
不 NSCalendarDayChanged正在发布,您正在发布通知。删除行
NotificationCenter.default.post(name: notificationName, object: nil)
并删除
if let _ = loadHW(){
assignments = loadHW()!
}
这是多余的。以下if - let
表达式完全相同。