Core Data Tutorial – Get The Row Count
Posted on 1 Feb ’12
Simple as it sound, it is that simple tutorial to get the row count using Core Data. It is one of the main attributes of your NSFetchRequest.
Please note, the following tutorial is NOT an introduction to Core Data or a walkthrough of its features. For that I would recommend Ray Wenderlich’s brilliant tutorials, and Apple’s resources. Use StackOverflow for any design questions that you may have. Other tutorials are also available on the tutorials page.
This tutorial will focus on one topic – how to fetch the row count from your datastore (in my case an sqlite3 db). I will walkthrough how I designed it, and how the code is implemented in XCode.
How to fetch row count
In your NSFetchRequest, as per Apple’s documentation, there is the standard line of code to execute the request. Something along the lines of:
NSArray *fetchResults = [managedObjectContext executeFetchRequest:request error:&error];
All you need to do is use the attribute countForFetchRequest instead of executeFetchRequest, as follows:
NSInteger count = [managedObjectContext countForFetchRequest:request error:&error];
The return value should be an NSInteger, rather than an NSArray and voilá.
You can even use them sequentially, however keep in mind that the number of requests on the database doesn’t get too complex.
Hope that is helpful and saves you some time searching the web.
For more Tutorials, check out my dedicated page here, which also lists a load of development and design resources (some free) that I found useful.