How to check a single time if UserDefaults is empt

2019-07-14 08:07发布

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.

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)
    }

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.

2条回答
看我几分像从前
2楼-- · 2019-07-14 08:45

Create an array within your view controller.

var dates = [NSDate]()

Then in viewDidLoad:

if let retrieved = userDefault.objectForKey("day") {
    dates = retrieved as! [NSDate]
}

Then reload your collection view

查看更多
萌系小妹纸
3楼-- · 2019-07-14 08:49

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
}
查看更多
登录 后发表回答