【问题标题】:Bulk update data in iOS 7 CoreDataiOS 7 CoreData 中的批量更新数据
【发布时间】:2014-09-17 07:22:04
【问题描述】:

有没有办法通过一个 SQL 查询来更新某个实体的所有对象? 不获取和运行循环。

比如喜欢跑步

UPDATE someEntity SET filed1 = value1 WHERE field2 = value2

【问题讨论】:

    标签: ios core-data ios7 core-data-migration


    【解决方案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];
    }
    

    【讨论】:

    • 是的,但这会将所有对象都带入内存!
    • 是的,没错,但是如果您正在寻找向后兼容的答案,那么您可以使用这个答案。
    【解决方案2】:

    在 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。

    此答案基于this post by Matthew Morey

    【讨论】:

    • 我遇到了一个问题,其中 result 和 requestError 都是 nil....并且 executeRequest:error: is undocumented...wat do
    猜你喜欢
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    相关资源
    最近更新 更多