2015-12-18 63 views
0

我試圖將我的Swift 1代碼轉換爲Swift 2.1.1代碼。 所以我想添加一個fetchRequest。在Swift中獲取請求2.1.1

在夫特1 I這樣做:

if let results = context.executeFetchRequest(fetchRequest, error:&error), 
    let managedObject = results.first as? NSManagedObject { 
     context.deleteObject(managedObject) 
    } 

let saveError: NSError? 
context.save(nil) 

var error: NSError? 
let fetchedResults = managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]? 
if let results = fetchedResults { 
     people = results 
    } 
    else { 
     print("Could not fetch \(error), \(error!.userInfo)") 
    } 

夫特2.1(第二請求 - >不工作):

do { 
    let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject] 
    // success if it gets here 
    if let results = fetchedResults { 
     people = results 
    } 
} catch let error as NSError { 
    // failed so print error 
    print("Error: \(error.localizedDescription)") 
} 

錯誤管線( if let results... & let fetchedResults...):

Initializer for conditional binding must have Optional type, not '[AnyObject]' 

Call can throw, but is not marked with 'try' and the error is not handled

錯誤的行(let fetchedResults...):

Call can throw, but is not marked with 'try' and the error is not handled

Cannot downcast from '[AnyObject]' to a more optional type '[NSManagedObject]?'

能否請你幫我翻譯成斯威夫特2.1.1嗎? 感謝您的幫助!

+0

尋求幫助時會有所幫助,以顯示你在哪裏遇到問題。這段代碼樣本給了你什麼錯誤信息,你認爲這些意思是什麼?你已經嘗試了什麼?否則很難知道什麼可以幫助你,這可以看作是爲你工作的請求。 – Jonah

+0

我用更多的信息更新了我的問題。 – 123

回答

1

您可以將其包裝在docatch塊中。如果let results行失敗,它將打印一個錯誤。

do { 
    let results = try context.executeFetchRequest(fetchRequest) 
    // success if it gets here 
    if let managedObject = results.first as? NSManagedObject { 
     context.deleteObject(managedObject) 
    } 
} catch let error as NSError { 
    // failed so print error 
    print("Error: \(error.localizedDescription)") 
} 

編輯

第二個請求:

do { 
    let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) 
    // success if it gets here 
    if let results = fetchedResults as? [NSManagedObject]{ 
     people = results 
    } 
} catch let error as NSError { 
    // failed so print error 
    print("Error: \(error.localizedDescription)") 
} 
+0

我在問題中加入了我的嘗試,但需要再次請您提供幫助。 – 123

+0

@ 123我更新了我的答案。這有幫助嗎? – Caleb

+0

是的。謝謝你的幫助! – 123