Swift编程中的NSErrorPointer错误等

45
var data: NSDictionary = 
    NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: error) as NSDictionary;

这行代码给我报错了

NSError is not convertable to NSErrorPointer.

所以我认为需要将代码更改为:

var data: NSDictionary =
     NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary;

我想把NSError error转换成NSErrorPointer,但是我得到了一个新的错误,而且无法理解它:

NSError! is not a subtype of '@|value ST4'
4个回答

69

自从Swift 1以来,这些类型和方法已经发生了很大变化。

  1. 前缀NS已被删除。
  2. 方法现在抛出异常而不是采用错误指针。
  3. 不建议使用NSDictionary,而应该使用Swift字典。

这将导致以下代码:

do {
    let object = try JSONSerialization.jsonObject(
        with: responseData,
        options: .allowFragments)
    if let dictionary = object as? [String:Any] {
        // do something with the dictionary
    }
    else {
        print("Response data is not a dictionary")
    }
}
catch {
    print("Error parsing response data: \(error)")
}

如果您不关心特定的解析错误:

let object = try JSONSerialization.jsonObject(
    with: responseData,
    options: .allowFragments)
if let dictionary = object as? [String:Any] {
    // do something with the dictionary
}
else {
    print("Response data is not a dictionary")
}
您的NSError必须定义为一个可选项,因为它可以是nil:
var error: NSError?

您还需要考虑解析时可能会出现错误导致返回 nil 或解析返回一个数组。为了解决这个问题,我们可以使用可选强制转换和 as? 操作符。

那么,以下是完整的代码:

var possibleData = NSJSONSerialization.JSONObjectWithData(
    responseData,
    options:NSJSONReadingOptions.AllowFragments,
    error: &error
    ) as? NSDictionary;

if let actualError = error {
    println("An Error Occurred: \(actualError)")
}
else if let data = possibleData {
   // do something with the returned data
}

3
如果解析JSON时出现错误并返回nil,则此操作将崩溃。请参见此答案:https://dev59.com/v2Af5IYBdhLWcg3w31-O#24333999。 - user1687195
我更新了答案以防止由解析错误引起的崩溃。 - drewag

13

如前所述,错误必须被定义为可选项。

然而,如果出现错误并返回nil时,此代码将会崩溃,其中"As NSDictionary"是罪魁祸首。

https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/AdoptingCocoaDesignPatterns.html

var data: NSDictionary =
 NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary;

您需要按照以下方式进行JSON解析:

var jsonError : NSError?

let jsonResult : AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &jsonError)

if let error = jsonError{
    println("error occurred: \(error.localizedDescription)")
}
else if let jsonDict = jsonResult as? NSDictionary{
    println("json is dictionary \(jsonDict)")
}
else if let jsonArray = jsonResult as? NSArray{
    println("json is an array: \(jsonArray)")
}

可以这样做。同时要记住,JSON 可以作为数组返回。你可以传递任何你喜欢的选项,而不是将 nil 传递给它,例如:

NSJSONReadingOptions.AllowFragments

如果您愿意的话。


1

现在是 beta-3 版本

var error: AutoreleasingUnsafePointer<NSError?> = nil

var data: NSDictionary = NSJSONSerialization.JSONObjectWithData( w, options:.AllowFragments, error: error ) as NSDictionary;

谢谢moby,'?'是不必要的。所以, var error: NSErrorPointer = nil - Satachito

0

请使用以下代码进行检查:

var error: AutoreleasingUnsafePointer<NSErrorPointer?>=nil
var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)
var err: NSError?
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
    println("Result\(jsonResult)")

尝试使用

 var error: AutoreleasingUnsafePointer<NSErrorPointer?>=nil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接