有没有办法通过一个SQL查询来运行某个实体的所有对象的更新? 不要获取和运行循环。
例如喜欢运行
UPDATE someEntity SET filed1 = value1 WHERE field2 = value2
答案 0 :(得分:3)
核心数据批量更新是在iOS 8上引入的:
NSBatchUpdateRequest *batchRequest = [NSBatchUpdateRequest batchUpdateRequestWithEntityName: [RSSItem entityName]];
batchRequest.propertiesToUpdate = @{NSStringFromSelector(@selector(read)): @YES};
batchRequest.resultType = NSStatusOnlyResultType; // NSStatusOnlyResultType is the default
batchRequest.affectedStores = @[...]; // Optional, stores this request should be sent to
batchRequest.predicate = [NSPredicate predicateWithFormat:@"..."]; // Optional, same type of predicate you use on NSFetchRequest
NSError *requestError;
NSBatchUpdateResult *result = (NSBatchUpdateResult *)[self.managedObjectContext executeRequest:batchRequest error:&requestError];
if (result) {
// Batch update succeeded
} else {
NSLog(@"Error: %@", [requestError localizedDescription]);
}
但是,它不会更改上下文:它会直接更改持久性存储。这意味着没有进行验证,您需要在之后更新UI。
答案 1 :(得分:1)
Mercelo的答案不适用于iOS-7,你可以
NSFetchRequest *fetchAllRSSItems = [NSFetchRequest fetchRequestWithEntityName:[RSSItem entityName]];
NSError *fetchError;
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchAllRSSItems error:&fetchError];
if (results == nil) {
NSLog(@"Error: %@", [fetchError localizedDescription]);
} else {
for (RSSItem *rssItem in results) {
rssItem.read = [NSNumber numberWithBool:YES];
}
[self saveManagedObjectContext];
}