NSCalendarDayChanged is posting without the day changing
应用程序委托中的以下代码应该每天一次向 assignments 数组添加一个新分配。问题是,每次打开应用程序时都会添加一个新任务,即使日期没有改变。似乎每次打开应用程序时 NSCalendarDayChanged 都会发布。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
var assignments = [Assignment]()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if let _ = loadHW(){ if let assignment = NSKeyedUnarchiver.unarchiveObject(withFile: Assignment.ArchiveURL.path) as? [Assignment]{ // Define identifier // Register to receive notification // Post notification
// Override point for customization after application launch.NSNotification.Name.NSCalendarDayChanged let dayOfTheWeek = Calendar(identifier: Calendar.Identifier.gregorian).component(.weekday, from: Date()) dateFormatter.dateFormat =”M/dd/YY” //Adds an assignment based on date comparisons
//adds assignment on first launch of app } if !isSuccessfulSave { //Diagnostic func loadHW() -> [Assignment]? { } |
我可以进行哪些更改以确保每天只创建一个作业?
- 记下您上次收到通知的时间(或使用上次作业的日期),然后在做任何其他事情之前将其与当前日期进行比较?
- 实际上,问题更可能是在添加观察者之后……您发布了该事件的通知!
- 为什么要取消归档同一个 Assignment 对象最多 3 次?
- @jcaron 真的!哎呀……对不起……
不是 NSCalendarDayChanged 正在发布,您正在发布通知。删除行
1
|
NotificationCenter.default.post(name: notificationName, object: nil)
|
也删除
1
2 3 |
if let _ = loadHW(){
assignments = loadHW()! } |
这是多余的。以下 if – let 表达式的作用完全相同。
来源:https://www.codenong.com/39856619/