我有一个使用CoreData存储Customer
个实体的应用程序。每个Customer
实体都有customerName
,customerID
和其他属性。
然后,我会显示仅显示Customers
和customerName
的所有customerID
的列表。
我可以通过执行获取请求来抓取所有Customer
实体来做到这一点,但是我只需要显示customerName
和customerID
属性。
问题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
个对象customerName
和customerID
。我只需要它返回所有Customer
个对象customerName
和customerID
。
问题2:
这是最好的方法吗?我的想法是数据库中最多可以有10k + Customer对象。因此,仅获取显示在表中而不是整个Customer
对象中所需的属性将是内存高效的。
然后,当在表中选择客户时,我获取整个Customer
对象以显示其详细信息。
但是,我已经读过,如果可以在不久的将来使用相应的实体,那么加载整个实体而不仅仅是它的属性也是一种好习惯。我想这个想法是单个获取请求优于两个。
感谢您的帮助。
答案 0 :(得分: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)
}
答案 1 :(得分:0)
随机,
问题2: 当你应该使用批量限制时,听起来你正在使用获取限制。批量限制是一种基本的游标机制。它们旨在有效地处理内存。
W.r.t。问题1,我非常相信以自然的方式编写应用程序,然后使用Instruments和其他工具来决定性能和内存优化。尝试让应用程序首先正确运行。然后快点。
安德鲁