We're sunsetting PodQuest on 2025-07-28. Thank you for your support!
Export Podcast Subscriptions
cover of episode 310. The iOS Apprentice 2- Checklists 09 - NSUserDefaults-2

310. The iOS Apprentice 2- Checklists 09 - NSUserDefaults-2

2016/1/8
logo of podcast iOSDevLog

iOSDevLog

Shownotes Transcript

To be fair, NSUserDefaults isn’t a true dictionary, but it acts like one.平心而论,NSUserDefaults不是一个真正的字典,但它像字典一样。This is what you are going to do:On the segue from the main screen (AllListsViewController) to the checklist screen (ChecklistViewController), you write the row index of the selected list into NSUserDefaults. This is how you’ll remember which checklist was active.(记住下标)You could have saved the name of the checklist instead of the row index, but what would happen if two checklists have the same name? Unlikely, but not impossible. Using the row index guarantees that you’ll always select the proper one.(名字会有冲突,最好有唯一标识)When the user presses the back button to return to the main screen, you have to remove this value from NSUserDefaults again. It is common to set a value such as this to -1 to mean “no value”.(返回时清空记录,例如 -1)Why -1? You start counting rows at 0, so you can’t use 0. Positive numbers are also out of the question, unless you use a huge number such as 1000000 – it’s very unlikely the user will make that many checklists. -1 is not a valid row index; and because it’s a negative value it looks weird, making it easy to spot during debugging.(If you’re wondering why you’re not using an optional for this – good question! – the answer is that NSUserDefaults cannot handle optionals. Sad face.)(为何不用 可空类型? 因为 NSUserDefaults 不支持)If the app starts up and the value from NSUserDefaults isn’t -1, the user was previously viewing the contents of a checklist and you have to manually perform a segue to the ChecklistViewController for the corresponding row.(如果有不为 -1 的值,需要手动跳转到上次打开界面)