2016-03-15 58 views
2

在SwiftCoreDataHelper.swift中,可以幫助我解決以下三個錯誤。我使用的是xcode 7,但它似乎是舊版xcode的代碼。提前致謝。xcode 7中的SwiftCoreDataHelper.swift錯誤

1。 。 。

line error: let items: NSArray = managedObjectContext.executeFetchRequest(<#T##request: NSFetchRequest##NSFetchRequest#>) error: Call can throw, but it is not marked with 'try' and the error is not handled

class func fetchEntities(className:NSString, withPredicate predicate:NSPredicate?, managedObjectContext:NSManagedObjectContext)->NSArray{ 
    let fetchRequest:NSFetchRequest = NSFetchRequest() 
    let entetyDescription:NSEntityDescription = NSEntityDescription.entityForName(className as String, inManagedObjectContext: managedObjectContext)! 

    fetchRequest.entity = entetyDescription 
    if predicate != nil { 
     fetchRequest.predicate = predicate! 
    } 

    fetchRequest.returnsObjectsAsFaults = false 
    let items: NSArray = managedObjectContext.executeFetchRequest(<#T##request: NSFetchRequest##NSFetchRequest#>) 

    return items 
} 

2。 。 。

行錯誤:如果managedObjectContext.save(無){

error: Nil is not compatible with expected argument type '()'

class func saveManagedObjectContext(managedObjectContext:NSManagedObjectContext)->Bool{ 
    if managedObjectContext.save(nil) { 
     return true 
    } 
    else { 
     return false 
    } 
} 

3。 。 。

line error: if storeCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error:&error) != nil {

error: Contextual type '[NSObject : AnyObject]' cannot be used with array literal

if storeCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error:&error) != nil { 

    if error != nil { 
     print(error!.localizedDescription) 
     abort() 
    } 
} 
+0

對不起。新手在這裏。感謝您的更正 –

+0

清楚地說明每個代碼的哪一行會生成編譯器錯誤。 – matt

+1

Both *「調用可以拋出,但它沒有用'try'標記,並且錯誤沒有被處理」*和*「無與預期的參數類型'()'不兼容'*表示你的代碼不適用於Swift 2中的**新錯誤處理**您會發現許多與該主題相關的問答,特別是第一條錯誤消息。例如:[Swift 2(executeFetchRequest):錯誤處理](http://stackoverflow.com/questions/30954722/swift-2-executefetchrequest-error-handling)。我強烈建議您閱讀當前Swift文檔中的錯誤處理。 –

回答

0
  1. 閱讀dotrythrowcatch。如果一個調用拋出,你應該把它放在一個do塊中,並用catch處理錯誤。
  2. 刪除無。預計沒有爭議。您可能需要處理拋出的錯誤。
  3. 不太清楚這裏的錯誤是什麼,但這又需要轉換爲Swift 2錯誤處理,應該看起來像這樣。請注意,錯誤參數已成爲拋出的錯誤。這是未經測試的承諾,它絕對是正確的。

    do { 
        let coordinator = try storeCoordinator.addPersistentStoreWithType(
         NSSQLiteStoreType, 
         configuration: nil, 
         URL: url, options: nil) 
    } catch { 
        print(error) 
        abort() 
    } 
    
+0

我已經做該做的嘗試扔,但現在我的錯誤是使用未解決的標識符的「項目」這是我的代碼: –

+0

做{ 設項=嘗試managedObjectContext.executeFetchRequest(fetchRequest) } {趕上 打印(「錯誤」 ) } 回報項目 } 做{ 讓項目=嘗試managedObjectContext.executeFetchRequest(fetchRequest) } {趕上 打印( 「錯誤」) } 退回項目 } –

+0

當您嘗試返回項目時,項目超出範圍。將'let items ='替換爲'return',並且您可能想要從catch塊內返回nil或[]。 –