【发布时间】:2016-07-13 00:44:46
【问题描述】:
我的应用计算日期和 NSDate() 之间的天数。当我发布它时,用户只能保存一个日期、一个标题和一张背景图片。
现在我有一个 UICollectionView 可以选择保存多个日期,它会通过将日期、标题和图像字符串附加到它们各自的数组来创建一个单元格。
应用程序已完全更改,因此我正在努力检查用户是否保存了日期,如果有,则将该信息添加到数组以创建单元格。
但是,我希望只检查一次 - 第一次从更新或全新安装打开应用程序时。
这是我的想法,顺便说一句,它不起作用。
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
if userDefault.objectForKey("day") == nil {
} else {
// Add the first date created from previous version
let day = userDefault.objectForKey("day") as? String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy hh:mm a"
let date = dateFormatter.dateFromString(day!)!
let date1 = dateFormatter.stringFromDate(date)
addDateToArray(date1)
// Add the since text
let text = userDefault.objectForKey("sinceText") as? String
addSinceLabelToArray(text!)
//Add the image background
let image = userDefault.objectForKey("khoury") as! String
addThemeToImagesArray(image)
}
上面的代码会返回 nil。我期待它创建第一个单元格,以便用户可以看到他们保存的日期。
【问题讨论】:
-
借此机会采用 Core Data 而非 NSUserDefaults 进行存储。当用户首次启动新版本时,检查 NSUserDefaults 值,将其迁移到您的核心数据,然后删除 NSUserDefaults 值。
-
“它不起作用”告诉我们关于您的问题的信息很少。你预期会发生什么,你看到了什么,你认为这意味着什么?
-
@Jonah 进行了编辑
-
cellForItemAtIndexPath是检索数据的错误位置。调用这个函数来显示数据;如果您的数组为空,则没有要显示的数据,也不会被调用。您应该在viewDidLoad中加载数据 -
然后您可以在 NSUserDefaults 中设置另一个布尔值,指示您是否已完成检查。
标签: ios arrays swift uicollectionview nsuserdefaults