简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM