在Swift中从CoreData中获取几列

时间:2015-11-25 10:24:34

标签: ios swift core-data

假设名为 TBL_person 的表格有4列,而我想获取仅 id 名称列的数据

enter image description here

在SQL中我可以这样做:

  

SELECT id,name FROM TBL_person ORDER BY id ASC

但是在SWIFT可以做些什么?

    let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let moContext:NSManagedObjectContext = appDel.managedObjectContext

    let fetchRequest = NSFetchRequest()

    let entityDescription = NSEntityDescription.entityForName("TBL_person", inManagedObjectContext: moContext)

    fetchRequest.entity = entityDescription

    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]

    do {
        let personList = try moContext.executeFetchRequest(fetchRequest) as! [ModelPerson]

        print("test------", personList.count)

    } catch {
        let fetchError = error as NSError
        print(fetchError)
    }

2 个答案:

答案 0 :(得分:1)

谢谢@Martin R.您的评论帮助我解决了问题。如有必要,可供其他人使用:

let entityDescription = NSEntityDescription.entityForName("TBL_person", inManagedObjectContext: moContext)

    fetchRequest.entity = entityDescription

    fetchRequest.propertiesToFetch = ["id","name"]
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]

    do {
        let personList = try moContext.executeFetchRequest(fetchRequest) as! [ModelPerson]

        print("test------", personList.count)

    } catch {
        let fetchError = error as NSError
        print(fetchError)
    }

答案 1 :(得分:1)

我在Core Data Programming Guide中找到了结果。希望能帮到你。 https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/FetchingObjects.html#//apple_ref/doc/uid/TP40001075-CH6-SW1

过滤结果

获取对象的真正灵活性在于获取请求的复杂性。首先,您可以向获取请求添加NSPredicate对象,以缩小返回的对象数。例如,如果您只想要具有FirstName Trevor的Employee对象,则将谓词直接添加到NSFetchRequest:

OBJECTIVE-C

NSString *name = @"Trevor";
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name == %@", name]];

SWIFT
let name = "Trevor"
fetchRequest.predicate = NSPredicate(format: "name == %@", name)

除了缩小要返回的对象外,还可以配置返回这些对象的方式。例如,您可以指示Core Data返回NSDictionary实例,而不是完全形成的NSManagedObject实例。此外,您可以配置NSFetchRequest,以便这些NSDictionary实例仅包含Employee实体上可用属性的子集。