-
Notifications
You must be signed in to change notification settings - Fork 223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add count() method to entities and optimize Core Data implementation #87
Conversation
… directly from an object type (e.g., SomeObjectClass.count()), rather than via all().count(). Optimized core data implementation of count() to use `NSManagedObjectContext.countForFetchRequest()` instead of loading all instances of the object into memory and counting them.
Hello @twobitlabs firstly thanks for your contribution. I agree with the performance fix I didn't think about it when I did the implementation. I've been reviewing it and thinking about the current library structure and I would change it a bit (but keeping the core idea):
var count: Int = 0
SugarRecord.operation(stackType!, closure: { (context) -> () in
count = context.count(self.objectClass!, predicate: self.predicate)
})
return count That way the user could do something like: Person.by("name", value: "Pedro").count() And the count method will use the internally generated NSPredicate to count People with Pedro as name. What do you think about it? 🎉 🎉 Thanks for all |
Ah nice catch on the predicates. I'll make that change and push. I agree it's a good idea to add this example to the documentation, as I'm not sure it's obvious. Is the wiki the right place for that? |
One thing I found slightly strange was that to create a predicate on a string field, I had to single-quote the string. The Predicate Programming Guide examples show that string matches need to be single-quoted. I think we may need to create a few versions of |
Totally agree @twobitlabs . I've created an issue for that: #88 |
Updated the Wiki @twobitlabs |
And 👍 to your last changes, got the idea quickly. I'm refactoring a bit the fetching methods to return a custom type other than an Array so I'll update it with these changes and support Realm with better performance. Thanks for all |
Add count() method to entities and optimize Core Data implementation
Although the SugarRecord wiki lists a
count()
method under "Objects querying", there is no such method--you have to callall().count()
.In Core Data, this is inefficient, as it loads all instances of the entity and then counts them. I've added a
count()
method toSugarRecordObjectProtocol
as is currently documented, so it can be more conveniently called directly from an object type (e.g., SomeObjectClass.count()).Also optimized the Core Data implementation of
count()
to useNSManagedObjectContext.countForFetchRequest()
which invokes a count(*) query on the data store instead of loading the entities and counting them.