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)];
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…