NSArray init(contentsOf:error:)

How to use the initializer? What's the type of error?

Replies

This looks like an error in the Swift versions of the macOS 10.13 SDK.


The old "NSArray(contentsOf:)" initializers are deprecated, but macOS 10.13 introduced a new initializer that properly throws an error. In the underlying Obj-C APIs, the difference between the old and the new methods is obvious, but they don't translate into Swift properly.


Your best choice is to avoid this initializer, and use a PropertyListDecoder to decode the file contents directly into an Array value, avoiding NSArray.


If you must use this initializer, it seems to work if you write something like this (Xcode 9.2):


let array = try NSArray(contentsOf: url, error: ())


but this will stop working once the SDK problem is fixed. BTW, you should submit a bug report about this!

I use

let productIDs = NSArray(contentsOf: url) as? [String]


similar to the guide updated in Aug. 2017. No deprecation warning in Xcode 9.2.


Thanks for the advice. Since you know more about this, why not report the bug so you can discuss with Apple?

Hmm, well, the old ones are documented as deprecated, but the header file says "will be deprecated", so there's no warning.


If you're loading the contents of a plist file from your app bundle as in the example you linked, then using the old initializer seems OK. There is never going to be an error unless something has gone very, very wrong, and then you'll have bigger problems. 🙂


For that reason, you might as well write:


let productIDs = NSArray(contentsOf: url) as! [String]


and save yourself the trouble of dealing with an optional result.


>> why not report the bug


Actually, I did report it. Bug #36242760.