pitou pitou - 3 months ago 11
Swift Question

set bool NSUserdefault in viewDidLoad

I'm making an app which use some bool data so I call

NSUserDefault
. But I'm facing problems:

I don't know how set it in
viewDidLoad

I made the followed code:

var defaults = NSUserDefaults.standardUserDefaults()

override func viewDidLoad() {
super.viewDidLoad()

if (defaults.objectForKey("lvlWon1") != nil)
{
defaults.setBool(false, forKey: "lvlWon1")
lvlWon1 = defaults.valueForKey("lvlWon1") as! Bool

}else {
defaults.setBool(false, forKey: "lvlWon1")
lvlWon1 = defaults.valueForKey("lvlWon1") as! Bool
}

//
if (defaults.objectForKey("lvlWon2") != nil)
{
defaults.setBool(true, forKey: "lvlWon2")
lvlWon2 = defaults.valueForKey("lvlWon2") as! Bool
}else
{
defaults.setBool(false, forKey: "lvlWon2")
lvlWon2 = defaults.valueForKey("lvlWon2") as! Bool
}
}


But when
lvlWon1
change to
true
,
lvlWon2
too.. I thing it's because I wrote:

if lvlWon1/lvlWon2 != nil it = true


I there a way to write:

defaults.objectForKey("lvlWon1") != nil{
lvlWon1.setBool(Bool, forKey...... // write Bool, not False cause it could be true too


Or maybe is there an other way to save a bool data?

Answer

code:

if (defaults.objectForKey("lvlWon1") != nil)

is not correct to make nil checking. Read about if let expression (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html)

Try this code:

ViewController.swift

import UIKit

class ViewController: UIViewController {

var defaults = NSUserDefaults.standardUserDefaults()

@IBOutlet weak var startSecondLevelButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    self.checkLevelsStatuses()
}

func checkLevelsStatuses() {

    startSecondLevelButton.enabled = false

    if let lvlWon1 = defaults.objectForKey("lvlWon1") as? Bool {
        // if true - level finished
        if (lvlWon1) {
            startSecondLevelButton.enabled = true
        }
    }else {
        defaults.setBool(false, forKey: "lvlWon1")
    }

    if let lvlWon2 = defaults.objectForKey("lvlWon2") as? Bool {

    } else {
        defaults.setBool(false, forKey: "lvlWon2")
    }

}

@IBAction func finishLevelOneButtonAction(sender: AnyObject) {
    defaults.setBool(true, forKey: "lvlWon1")
    checkLevelsStatuses()
}

@IBAction func resetLevels(sender: AnyObject) {
    defaults.setBool(false, forKey: "lvlWon1")
    defaults.setBool(false, forKey: "lvlWon2")
    checkLevelsStatuses()
}
}

Main.storyboard

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15G31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
    <deployment identifier="iOS"/>
    <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
    <!--View Controller-->
    <scene sceneID="tne-QT-ifu">
        <objects>
            <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_39101363" customModuleProvider="target" sceneMemberID="viewController">
                <layoutGuides>
                    <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                    <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                </layoutGuides>
                <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                    <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
                    <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                    <subviews>
                        <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="B72-XL-JYT">
                            <rect key="frame" x="283" y="285" width="35" height="30"/>
                            <state key="normal" title="reset"/>
                            <connections>
                                <action selector="resetLevels:" destination="BYZ-38-t0r" eventType="touchUpInside" id="WNg-pB-qnW"/>
                            </connections>
                        </button>
                        <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="3Y8-in-IDf">
                            <rect key="frame" x="261" y="251" width="80" height="30"/>
                            <state key="normal" title="start level 2"/>
                        </button>
                        <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="v5J-O7-aIu">
                            <rect key="frame" x="259" y="213" width="83" height="30"/>
                            <state key="normal" title="finish level 1"/>
                            <connections>
                                <action selector="finishLevelOneButtonAction:" destination="BYZ-38-t0r" eventType="touchUpInside" id="HvB-0C-e6F"/>
                            </connections>
                        </button>
                    </subviews>
                    <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
                    <constraints>
                        <constraint firstItem="B72-XL-JYT" firstAttribute="top" secondItem="3Y8-in-IDf" secondAttribute="bottom" constant="4" id="H31-DZ-ves"/>
                        <constraint firstItem="3Y8-in-IDf" firstAttribute="top" secondItem="v5J-O7-aIu" secondAttribute="bottom" constant="8" symbolic="YES" id="HYm-4A-mUC"/>
                        <constraint firstItem="v5J-O7-aIu" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="R2k-vf-StV"/>
                        <constraint firstItem="3Y8-in-IDf" firstAttribute="centerX" secondItem="B72-XL-JYT" secondAttribute="centerX" id="Y4H-7u-xTQ"/>
                        <constraint firstItem="B72-XL-JYT" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="cL6-Pb-lPh"/>
                        <constraint firstItem="v5J-O7-aIu" firstAttribute="centerX" secondItem="3Y8-in-IDf" secondAttribute="centerX" id="h8t-WH-vVg"/>
                    </constraints>
                </view>
                <connections>
                    <outlet property="startSecondLevelButton" destination="3Y8-in-IDf" id="D8b-7J-F0Z"/>
                </connections>
            </viewController>
            <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
        </objects>
    </scene>
</scenes>
</document>
Comments