简体   繁体   中英

Trying to add dictionary to nsmutable array in swift getting fatal error: unexpectedly found nil while unwrapping an Optional value

I am trying to create a NSMutableArray and add dictionary values from db (using fm db result set) then I got this error:

"fatal error: unexpectedly found nil while unwrapping an Optional value ".

Please give tips to solve this issue.

Code:

var arrCategory :NSMutableArray!

while rs.next(){

    arrCategory.addObject(rs.resultDictionary())
}

Before add dictionary, you should check that it is nil or not:

 while rs.next(){
     if(rs.resultDictionary() != nil){
         arrCategory.addObject(rs.resultDictionary())
     }
 }

It is because you are putting nil in the NSMutableArray which is not allowed. Some where rs.resultDictionary is returning nil.If that should not be the case check that out. Meanwhile the following answer would work. THE BETTER METHOD keeping in view the spirit of Swift language would be:

while rs.next()
{
    if let result = rs.resultDictionary
    {
         arrCategory.addObject(result) ;
    }

}

In addition to checking that rs.resultDictionary isn't nil, make sure you have allocated the mutable array to begin with. In the code you posted, it is only declared:

var arrCategory:NSMutableArray!

...but it is not clear if you ever allocated it or not; eg:

arrCategory = NSMutableArray()

Also, there's a chanve rs is nil , not just resultDictionary (impossible to tell witohut seeing your full code), so perhaps the check should be:

if let rs = rs {

    while rs.next(){

        if let result = rs.resultDictionary {
            arrCategory.addObject(result)
        }
    }
}

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