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

How to turn objects into NSMutableArray ? I archived NSMutableArray.

Bogdan Bogdanov
  • 882
  • 11
  • 36
  • 79

1 Answers1

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)
    // ...
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • @BogdanBogdanov: Strange, I tested it. Are you sure that the archived object is a *mutable* array? Does it work with `as? NSArray` ? – Martin R Nov 22 '14 at 15:41
  • ops No it wasn't NSMutableArray.. sorry my mistake it works :) – Bogdan Bogdanov Nov 22 '14 at 15:44
  • 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 – Doug Mead Feb 24 '16 at 16:07
  • @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. – Martin R Feb 24 '16 at 17:23
  • 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? – Doug Mead Feb 24 '16 at 17:26