Search code examples
core-datanspredicatensmanagedobject

NSPredicate to return ANY on self


Is there a method (NSPredicate or other function) that returns ANY single existing NSManagedObject. Could also be the count of an entity type. No further requirements other than mere existence on self.

NSPredicate *fetch = [NSPredicate predicateWithFormat: "@ANY"]

....
[fetch setEntity:entityDescription];
[fetch setPredicate: predicate];
[fetch setFetchLimit:1];

Note that this is the 'root' object, thus no instance at this boot stage.


Solution

  • I am not sure if I understand your question correctly, but to get a one (arbitrary) object of your entity just don't add a predicate to the fetch request and set the fetch limit to one:

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"YourEntity"];
    [request setFetchLimit:1];
    
    NSError *error;
    NSArray *result = [context executeFetchRequest:request error:&error];
    if (result == nil) {
        // Error executing fetch request
    } else if ([result count] == 0) {
        // Found none
    } else {
        // Found one
        NSManagedObject *obj = result[0];
    }