如果UserDefaults为空,如何检查一次 [英] How to check a single time if UserDefaults is empty

查看:232
本文介绍了如果UserDefaults为空,如何检查一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用计算从日期到NSDate()之间的天数。当我发布它时,用户只能保存一个日期,标题和背景图片。

My app counts the days between a date and NSDate(). When I released it, a user could only save one date, a title and a background image.

现在,我有一个UICollectionView,可以选择保存多个日期,它将通过在其各自的数组中附加日期,标题和图像字符串来创建一个单元格。

Now I have a UICollectionView with the option to save more than one date, and it will create a cell by appending a date, title and image string to their respective arrays.

该应用程序已完全更改,因此我在努力检查用户是否已保存日期,如果有的话,则将该信息添加到数组中

The app has been completely changed, so I'm struggling with how to check whether a user has saved a date, and if they have, add that info to the arrays to create a cell.

但是,我希望只检查一次-第一次从更新或全新安装打开应用程序。

But, I want this to only been checked once - the first time the app is opened from update or fresh install.

这是我的想法,它不能正常工作。

Here is my thinking about it, it doesn't work by the way.

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。我希望它可以创建第一个单元格,以便用户可以看到他们保存的日期。

What happens with the code above is it returns nil. I am expecting it to create the first cell, so that the user can see the date they have saved.

推荐答案

您可以使用 NSUserDefaults 中的另一个布尔值可检测首次运行:

You can use another boolean value in NSUserDefaults to detect the first run:

let defaults = NSUserDefaults.standardUserDefaults()

if (!defaults.boolForKey("migrated")) {
    defaults.setBool(true, forKey: "migrated")
    // ... anything else
}

这篇关于如果UserDefaults为空,如何检查一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆