objective-c Cocoa Core Data 计算实体的有效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1134289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:55:20  来源:igfitidea点击:

Cocoa Core Data efficient way to count entities

objective-ccore-data

提问by erazorx

I read much about Core Data.. but what is an efficient way to make a count over an Entity-Type (like SQL can do with SELECT count(1) ...). Now I just solved this task with selecting all with NSFetchedResultsControllerand getting the count of the NSArray! I am sure this is not the best way...

我读了很多关于 Core Data .. 但对实体类型进行计数的有效方法是什么(就像 SQL 可以用 SELECT count(1) ...)。现在我刚刚通过选择全部NSFetchedResultsController并获取NSArray! 我确定这不是最好的方法......

回答by Barry Wark

I don't know whether using NSFetchedResultsController is the most efficient way to accomplish your goal (but it may be). The explicit code to get the count of entity instances is below:

我不知道使用 NSFetchedResultsController 是否是实现目标的最有效方法(但可能是)。获取实体实例数的显式代码如下:

// assuming NSManagedObjectContext *moc

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:moc]];

[request setIncludesSubentities:NO]; //Omit subentities. Default is YES (i.e. include subentities)

NSError *err;
NSUInteger count = [moc countForFetchRequest:request error:&err];
if(count == NSNotFound) {
  //Handle error
}

[request release];

回答by Jim Correia

To be clear, you aren't counting entities, but instances of a particular entity. (To literally count the entities, ask the managed object model for the count of its entities.)

需要明确的是,您计算的不是实体,而是特定实体的实例。(要从字面上计算实体,请向托管对象模型询问其实体的数量。)

To count all the instances of a given entity without fetching all the data, the use -countForFetchRequest:.

要在不获取所有数据的情况下计算给定实体的所有实例,请使用-countForFetchRequest:.

For example:

例如:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity: [NSEntityDescription entityForName: entityName inManagedObjectContext: context]];

NSError *error = nil;
NSUInteger count = [context countForFetchRequest: request error: &error];

[request release];

return count;

回答by Suragch

Swift

迅速

It is fairly easy to get a count of the total number of instances of an entity in Core Data:

在 Core Data 中获取实体实例的总数相当容易:

let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "MyEntity")
let count = context.countForFetchRequest(fetchRequest, error: nil)

I tested this in the simulator with a 400,000+ object count and the result was fairly fast (though not instantaneous).

我在模拟器中用 400,000+ 个对象数对此进行了测试,结果相当快(虽然不是即时的)。

回答by Oscar Salguero

I'll just add that to make it even more efficient... and because its just a count, you don't really need any property value and certainly like one of the code examples above you don't need sub-entities either.

我将添加它以使其更有效......并且因为它只是一个计数,您实际上并不需要任何属性值,当然就像上面的代码示例之一一样,您也不需要子实体。

So, the code should be like this:

所以,代码应该是这样的:

int entityCount = 0;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntity" inManagedObjectContext:_managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setIncludesPropertyValues:NO];
[fetchRequest setIncludesSubentities:NO];
NSError *error = nil;
NSUInteger count = [_managedObjectContext countForFetchRequest: fetchRequest error: &error];
if(error == nil){
    entityCount = count;
}

Hope it helps.

希望能帮助到你。

回答by Yuriy Pavlyshak

I believe the easiest and the most efficient way to count objects is to set NSFetchRequestresult type to NSCountResultTypeand execute it with NSManagedObjectContext countForFetchRequest:error:method.

我相信计数对象的最简单和最有效的方法是将NSFetchRequest结果类型设置为NSCountResultType并使用NSManagedObjectContext countForFetchRequest:error:方法执行它。

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:entityName];
fetchRequest.resultType = NSCountResultType;
NSError *fetchError = nil;
NSUInteger itemsCount = [managedObjectContext countForFetchRequest:fetchRequest error:&fetchError];
if (itemsCount == NSNotFound) {
    NSLog(@"Fetch error: %@", fetchError);
}

// use itemsCount

回答by jarora

I wrote a simple utility method for Swift 3 to fetch the count of the objects.

我为 Swift 3 编写了一个简单的实用方法来获取对象的数量。

static func fetchCountFor(entityName: String, predicate: NSPredicate, onMoc moc: NSManagedObjectContext) -> Int {

    var count: Int = 0

    moc.performAndWait {

        let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: entityName)
        fetchRequest.predicate = predicate
        fetchRequest.resultType = NSFetchRequestResultType.countResultType

        do {
            count = try moc.count(for: fetchRequest)
        } catch {
            //Assert or handle exception gracefully
        }

    }

    return count
}

回答by Philippe H. Regenass

In Swift 3

在斯威夫特 3

  static func getProductCount() -> Int {
    let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Product")
    let count = try! moc.count(for: fetchRequest)
    return count
}

回答by Fattie

It's really just this:

真的只是这样:

let kBoat = try? yourContainer.viewContext.count(for: NSFetchRequest(entityName: "Boat"))

"Boat" is just the name of the entity from your data model screen:

“Boat”只是数据模型屏幕中实体的名称:

enter image description here

在此处输入图片说明

What is the global yourContainer?

什么是全局yourContainer

To use core data, at some point in your app, one time only, you simply go

要使用核心数据,在您的应用程序中的某个时刻,仅一次,您只需

var yourContainer = NSPersistentContainer(name: "stuff")

where "stuff" is simply the name of the data model file.

其中“stuff”只是数据模型文件的名称。

enter image description here

在此处输入图片说明

You'd simply have a singleton for this,

你只需要一个单身人士,

import CoreData
public let core = Core.shared
public final class Core {
    static let shared = Core()
    var container: NSPersistentContainer!
    private init() {
        container = NSPersistentContainer(name: "stuff")
        container.loadPersistentStores { storeDescription, error in
            if let error = error { print("Error loading... \(error)") }
        }
    }

    func saveContext() {
        if container.viewContext.hasChanges {
            do { try container.viewContext.save()
            } catch { print("Error saving... \(error)") }
        }
    }
}

So from anywhere in the app

所以从应用程序的任何地方

core.container

is your container,

是你的容器,

So in practice to get the count of any entity, it's just

所以在实践中要获得任何实体的数量,它只是

let k = try? core.container.viewContext.count(for: NSFetchRequest(entityName: "Boat"))

回答by Umit Kaya

If you want to find count for specific predicated fetch, i believe this is the best way:

如果您想查找特定谓词获取的计数,我相信这是最好的方法:

NSError *err;
NSUInteger count = [context countForFetchRequest:fetch error:&err];

if(count > 0) {
NSLog(@"EXIST"); 
} else {
NSLog(@"NOT exist");
}