Rahul
Rahul

Reputation: 3

App crashing on checking count NSMutableArray

the app crashes on checking for count of NSMutablearray if it is nil,i am not getting how to handle it, i am new to ios

let userDefaults: UserDefaults? = UserDefaults.standard
    let array  = userDefaults?.object(forKey: "purchaselist") as? NSMutableArray
    for i in 0..<array!.count {
}

Upvotes: 0

Views: 79

Answers (1)

PPL
PPL

Reputation: 6555

You should check for nil also,

if let array = userDefaults?.object(forKey: "purchaselist") as? [Any], !array.isEmpty {
    //Your code goes here
}

You can do this way also,

if let array = userDefaults?.object(forKey: "purchaselist") as? NSMutableArray {
    if array.count != 0 {
        //Your code goes here
    } else {
        //array count zero 
    }
} else {
    //Your array is nil
}

FYI. Code is not tested, it is just information.

Upvotes: 2

Related Questions