TrentinPriebe
TrentinPriebe

Reputation: 41

NSFetchRequest Return object first time it is run but not subsequent times

I have a set of objects and for each object in this set I am calling a method that has an NSFetchRequest inside of it. This NSFetchRequest is used to fetch an object based on an id that is passed into the method. For each of my objects I call this method on if it is the first time the id has been used in the predicate of the NSFetchRequest it returns the correct object, each time after that if that id is used again it returns nil. I am very confused by this and can't find anything on why this happens or what I am doing incorrectly. Any help would be greatly appreciated.

Here is the code for my NSFetchRequest:

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

[request setEntity:[NSEntityDescription entityForName:@"Styles" inManagedObjectContext:[self managedObjectContext]]];

[request setPredicate:[NSPredicate predicateWithFormat:@"style_id == %@", style_id]];

NSError *error = nil;

Styles *r_styles = [[[self managedObjectContext] executeFetchRequest:request error:&error] lastObject];

[request release]; 

Upvotes: 2

Views: 474

Answers (2)

TrentinPriebe
TrentinPriebe

Reputation: 41

I figured out my issue. I was passing my id as an NSString when I should have been passing it as an NSNumber. Changing it to an NSNumber solved my issue.

Upvotes: 2

TechZen
TechZen

Reputation: 64428

Your fetch execution has two sources of a nil. executeFretchRequest will return nil if an error occurs. lastObjectwill return nil if an array is empty.

There is nothing in particular wrong with this code but you should always trap the error return of a fetch if you have problems. That will usually tell you the source of the problem.

Upvotes: 1

Related Questions