9

I'm trying to update an NSError object with more information. For example, an api call may fail and I want to update the error object returned from the api class with view controller information (method name that caused error, client message, any additional info). There isn't a setter method for the UserInfo dictionary and trying to set a value for the dictionary raises an exception (Not key value code compliant I believe). I thought about creating a new NSError object with the updated user info, but I wasn't sure if I might lose information.

Question

What's the best way to update the user info dictionary of an NSError object?

4

3 に答える 3

10

迅速な拡張機能を使えば簡単です:

extension NSError {

  func addItemsToUserInfo(newUserInfo: Dictionary<String, String>) -> NSError {

    var currentUserInfo = userInfo
    newUserInfo.forEach { (key, value) in
      currentUserInfo[key] = value
    }
    return NSError(domain: domain, code: code, userInfo: currentUserInfo)
  }
}

利用方法:

var yourError = NSError(domain: "com.app.your", code: 999, userInfo: nil)
yourError = yourError.addItemsToUserInfo(["key1":"value1","key2":"value2"])
于 2016-04-08T12:29:37.867 に答える