0

我有一个使用 CoreData 来存储Customer实体的应用程序。每个Customer实体都有customerNamecustomerID和其他属性。

然后,我显示所有Customers仅显示其customerName和的列表customerID

我可以通过执行获取请求来抓取所有Customer实体来做到这一点,但是我只需要显示customerNameandcustomerID属性。

问题 1: 我尝试使用setPropertiesToFetch仅指定这些属性,但每次它只返回数组中的 1 个对象。

这是我的方法的样子:

    NSFetchRequest *fetchRequest = [NSFetchRequest new];


    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Customer" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    NSDictionary *entProperties = [entity propertiesByName];

    [fetchRequest setResultType:NSDictionaryResultType];
    [fetchRequest setReturnsDistinctResults:YES];

    [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:[entProperties objectForKey:@"customerName"],[entProperties objectForKey:@"customerID"], nil]];

    [fetchRequest setFetchLimit:30];

    NSError *error;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    NSLog(@"fetched objects count = %d", [fetchedObjects count]);

    if (error) {
        NSLog(@"Error performing fetch = %@", [error localizedDescription]);
        return nil;
    } else {
        NSLog(@"successful fetch of customers");
        for( NSDictionary* obj in fetchedObjects ) {
            NSLog(@"Customer: %@", [obj objectForKey:@"customerName"]);
        }
        return fetchedObjects;
    }

返回的一个对象是可以的,所以我知道它正在抓取至少一个Customer对象customerNamecustomerID. 我只需要它来返回所有Customer对象customerNamecustomerID.

问题2:

这是最好的方法吗?我的想法是数据库中可能有多达 10k+ 个 Customer 对象。因此,仅获取所需的属性以显示在表中而不是整个Customer对象中会节省内存。

然后,当在表中选择客户时,我会获取整个Customer对象以显示其详细信息。

但是,我读到如果可以在不久的将来使用相应的实体,加载整个实体而不是仅仅加载它的属性也是一个好习惯。我想这个想法是单个获取请求比两个更好。

谢谢您的帮助。

4

2 回答 2

2

对于问题 1:这是我用 swift 编写的示例代码。我不断测试CoreData API,找到了这种调用方式。希望能帮到你。

let fetchRequest = NSFetchRequest<NSDictionary>(entityName: "Customer")
fetchRequest.resultType = .dictionaryResultType
fetchRequest.propertiesToFetch = [
    #keyPath(Customer.customerID),
    #keyPath(Customer.customerName)
]

let customers: [NSDictionary]
do {
    customers = try managedObjectContext.fetch(fetchRequest)
    customers.forEach {
        print("CustomerID: \($0["customerID"]), CustomerName: \($0["customerName"])")
    }
} catch {
    print(error.localizedDescription)
}
于 2017-02-18T13:43:59.250 回答
0

random,

Question 2: It sounds like you are using fetch limits when you should be using batch limits. Batch limits are a basic cursoring mechanism. They are designed to handle memory efficiently.

W.r.t. Question 1, I'm a big believer in just writing the app in the natural way and then using Instruments and other tools to decide upon performance and memory optimizations. Try getting the app to run correctly first. Then make it fast.

Andrew

于 2013-02-15T04:58:41.040 回答