错误代码有错误:nil / nil / error

时间:2015-12-09 04:59:11

标签: swift error-handling

开始在SWIFT学习编码,每次我使用错误方法时都会出现此错误,请帮助

    var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    var request = NSFetchRequest(entityName: "Pattern")
    var results = context.executeFetchRequest(request, error:nil) // Extra argument 'error' in code
    if results != nil {

    }

}

func createTestPatterns(){
    var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    var pattern = NSEntityDescription.insertNewObjectForEntityForName("Pattern", inManagedObjectContext: context) as! Pattern
    pattern.name = "Blue Mushroom"
    context.save(nil) //call can throw but it is not marked with 'try' and the error is not handled
}

我该怎么办,请帮助。

2 个答案:

答案 0 :(得分:0)

func save()抛出

save方法抛出异常。请参阅link

这可以按如下方式处理

do
{
  try context.save()
}
catch let error
{
    print(error)
}

答案 1 :(得分:0)

使用Swift 2.0,他们为Error Handling引入了do/try/catch

不要使用error参数,而是声明它:

do {
    try var results = context.executeFetchRequest(request)
} catch let error as NSError {
    // Handle errors
}

save方法相同。

do {
    try context.save()
} catch let error as NSError {
   // Handle error
}