3
var objects: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(data)

How to turn objects into NSMutableArray ? I archived NSMutableArray.

1 Answer 1

7

Just downcast the result to NSMutableArray:

if let objects = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSMutableArray {
    // ...
} else {
    // failed
}

If the archived object is an (immutable) NSArray then you have to create a mutable copy:

if let array = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSArray {
    let objects = NSMutableArray(array: array)
    // ...
}
Sign up to request clarification or add additional context in comments.

5 Comments

@BogdanBogdanov: Strange, I tested it. Are you sure that the archived object is a mutable array? Does it work with as? NSArray ?
ops No it wasn't NSMutableArray.. sorry my mistake it works :)
Seems to me like casting to [AnyObject?] would be more "Swifty". I'm interested in what happens when you set an NSMutableArray to a let since you cannot change a let.. therefore making it a an NSArray
@DougMead: NSMutableArray is a reference type. Even if you assign it with let, you can modify the referenced (mutable) array. It does not make it an NSArray.
That makes sense. I guess I'm confusing syntactic sugar with actually assigning an NSMutableArray reference. I definitely remember seeing that let creates NSArrays and var creates NSMutableArrays in swift.. Am I correct in my assumption?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.