Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

iphone - How to fetch only the first record in Core Data?

I am using Core Data and I only want to fetch the first record in my dataset, is it possible?

question from:https://stackoverflow.com/questions/1197593/how-to-fetch-only-the-first-record-in-core-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the setFetchLimit: method on NSFetchRequest to limit the number of records fetched. So if you only want the first record:

// Given some existing NSFetchRequest *request and NSManagedObjectContext *context:
[request setFetchLimit:1];
NSError *error;
NSArray *results = [context executeFetchRequest:request error:&error];

Note that the call to executeFetchRequest:error: will still return an NSArray; you still need to pull the first object off the array before you can work with it, even though it's an array of size 1.

Another, less efficient method: Depending on your store type, limiting the fetch may produce dramatic performance speedups. If it doesn't, however, or you're not that worried about performance, and you might use more data later, you can just pull the first object off the array ahead of time:

// Given some existing result NSArray *results:
NSManagedObject *firstManagedObject = [results firstObject];

If you're sure that the array has an object in it, you can even get it into another array (for use in a UITableViewController, for example) by doing this:

// Again, with some NSArray *results:
NSArray *singleObjectResult = [results subarrayWithRange:NSMakeRange(0, 1)];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...