JUANM4
JUANM4

Reputation: 344

How get an object from core data by indexed attribute?

I have one entity, called user, in core data. This entity have 3 attributes (username, token, date)

In the entity, the attribute "username" have check indexed.

I Know how get an array of elements using a Fetch, but I would like how get the object directly(I don't want an array with one object) searching by indexed attribute.

Thanks!!!

Upvotes: 0

Views: 858

Answers (1)

Rajesh
Rajesh

Reputation: 960

You can do like this

NSFetchRequest *request = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity =

    [NSEntityDescription entityForName:@"user"

                inManagedObjectContext:managedObjectContext];

    [request setEntity:entity];



    NSPredicate *predicate =

    [NSPredicate predicateWithFormat:@"username == %@", targetUsername];

    [request setPredicate:predicate];



    NSError *error;

    NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];

    if (array != nil) {
        NSLog("%@", [array firstObject]);

    }

    else {

        // Deal with error.

    }

Upvotes: 2

Related Questions