将Core Data的结果直接返回给Class

时间:2014-11-15 20:24:04

标签: ios core-data swift

我是Swift和iOS开发的新手。这对我来说可能是一个简单的误解。

我正在使用核心数据。我的实体中有四个属性: “title”类型字符串 “经度”,“纬度”类型十进制 “timestamp”类型日期

在下面的代码中,我收到错误“'[Locations]'无法转换为'()'”。

import UIKit
import CoreData

@objc(Locations)
class Locations: NSManagedObject {

    @NSManaged var title:String
    @NSManaged var longitude:Double
    @NSManaged var latitude:Double
    @NSManaged var timestamp:NSDate

    class func getAllLocations(){
        let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
        let context:NSManagedObjectContext = appDel.managedObjectContext!

        var request = NSFetchRequest(entityName: "Locations")
        request.returnsObjectsAsFaults = false

        var results:NSArray = context.executeFetchRequest(request, error: nil)!

        return results as [Locations]

    }
}

1 个答案:

答案 0 :(得分:1)

编译器抱怨,因为你没有为你的函数指定返回类型, 它应该是

class func getAllLocations() -> [Locations] { ... }

还有一些不必要的类型注释,所有对象都可以 声明为常量:

class func getAllLocations() -> [Locations] {
    let appDel =  (UIApplication.sharedApplication().delegate as AppDelegate)
    let context = appDel.managedObjectContext!

    let request = NSFetchRequest(entityName: "Locations")
    request.returnsObjectsAsFaults = false

    let results = context.executeFetchRequest(request, error: nil)!
    return results as [Locations]
}

另请注意

let results = context.executeFetchRequest(request, error: nil)!
如果执行获取请求失败,

将抛出运行时异常。 您应该使用可选绑定和一些错误处理或回退, 例如

if let results = context.executeFetchRequest(request, error: nil) as? [Locations] {
    return results
} else {
    // Failed, return empty list. (Alternatively, report error.)
    return []
}