Search code examples
iosnsmutablearrayimmutabilitymutableswift2

[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'


IDK what is happening. I am just adding a value in my array.

Here is the code:

dispatch_async(dispatch_get_main_queue(), { () -> Void in
    let requestedURL = NSString(string: url_to_req)
    print(requestedURL.substringFromIndex(36))
    if requestedURL.substringFromIndex(36) == "forum"{
        returnValue = (parseJSON["_id"] as? String)!
        print("Here is id of posted question: '\(returnValue)'")
        if (NSUserDefaults.standardUserDefaults().objectForKey("PostedQuesIds") != nil){
            self.postedQuestionIds = NSUserDefaults.standardUserDefaults().objectForKey("PostedQuesIds") as? NSMutableArray
        }

        print("Total count of array '\(self.postedQuestionIds)")

        self.postedQuestionIds?.addObject(returnValue)// overhere my app gets a crash
        // self.postedQuestionIds = NSMutableArray(object: returnValue)
        NSUserDefaults.standardUserDefaults().setObject(self.postedQuestionIds, forKey: "PostedQuesIds")
        NSUserDefaults.standardUserDefaults().synchronize()                            
    }
})

For the doubts, i have also tried the code below like if i have forgotten things about nsmutablearray

var name = "abc"
let firstname = "dd"
let lastname = "zz"

let arr:NSMutableArray? = NSMutableArray()

arr?.addObject(name)
name = "ABC"

arr?.removeObjectAtIndex(0)
arr?.addObject(firstname)
arr?.addObject(lastname)
arr?.addObject(name)

print("Here is complete array '\(arr)'")

This works fine. Please help me it looks that i am missing things and couldn't able to find them. Your efforts would be highly appreciated.


Solution

  • It seems that if you retrieve the array from NSUserDefaults, it becomes to immutable one. Try this instead.

    let array = NSUserDefaults.standardUserDefaults().objectForKey("PostedQuesIds") as! NSArray
    self.postedQuestionIds = NSMutableArray(array: array)