2016-06-22 54 views
1

我有executeFetchRequest一些問題斯威夫特:executeFetchRequest:無法將類型的價值 '任何對象'

import UIKit 
import CoreData 

class BeaconDB: NSObject { 

    var addStatus: BeaconAddStatus! 


    enum BeaconAddStatus{ 
      case DUPLICATE_IN_AD 
      case ADDED_SUCCESSFULL 
      case ERROR_IN_ADD 
    } 


    func addNewBeacon(beacon: BeaconData) -> BeaconAddStatus{ 
      print("ADDNewBeacon") 
      print("uuid: %@ \(beacon.uuid)") 

    let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    let context: NSManagedObjectContext = appDelegate.managedObjectContext 

    let entityDesc: NSEntityDescription = NSEntityDescription.entityForName("Beacon", inManagedObjectContext: context)! 
    let request: NSFetchRequest = NSFetchRequest() 
    let predSearch: NSPredicate = NSPredicate(format: "(uuid = %@) AND (major = %@) AND (minor = %@) \(beacon.uuid), \(beacon.major), \(beacon.minor)") 

    request.entity = entityDesc 
    request.predicate = predSearch 

    do { 
     let existingBeacon: Beacons = try context.executeFetchRequest(request) 
     // success ... 
    } catch let error as NSError { 
     // failure 
     print("Fetch failed: \(error.localizedDescription)") 
    } 

} 

} 

了Mv信號燈類是NSManagedObject

import UIKit 

    import CoreData 

    class Beacons: NSManagedObject { 

     dynamic var major : NSNumber = 0.0 
     dynamic var minor : NSNumber = 0.0 
     dynamic var name : NSString = "" 
     dynamic var uuid : NSString = "" 
    } 

但它從該行

的錯誤
let existingBeacon: Beacons = try context.executeFetchRequest(request) 

無法將類型[ '任何對象']的值爲指定類型的 '燈塔'

幫我請 謝謝:))

回答

3

兩個問題:

  • executeFetchRequest回報總是對象的數組
  • 您必須施放該類型。

let existingBeacons = try context.executeFetchRequest(request) as! [Beacons] 

無法轉換值類型的...指定類型...通常意味着編譯器通過強制轉換類型需要幫助,或者是沒有關係的。

PS:建議以單數形式命名核心數據實體以避免混淆。

+0

它的工作。非常感謝你 –

相關問題