toom
toom

Reputation: 13347

ios and coredata: NSPredicate does not work on fetch request

I have the following class

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface Bankdaten : NSManagedObject

@property (nonatomic, retain) NSString * blz;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * https;

@end

and the implementation

#import "Bankdaten.h"

@implementation Bankdaten

@dynamic blz;
@dynamic name;
@dynamic https;

@end

I checked that the data for this object is correctly save by core data in a corresponding table in my sqlite database.

Now, I want to fetch a specific object by doing this request:

-(Bankdaten*) ladeBankdaten:(NSString*) blz
{
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Bankdaten" inManagedObjectContext:moc];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(blz == '%@')", blz];
    [request setPredicate:predicate];

    NSError *error = nil;
    NSArray *array = [moc executeFetchRequest:request error:&error];
    if (array == nil) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    if( [array count] == 0 )
        return nil;
    return [array objectAtIndex:0];
}

The problem: In that case the array contains always zeros objects and so my method returns nil although the blz parameter must match a certain value in the database. So the fetch request should be positive. If I comment the line

[request setPredicate:predicate];

Such that there is no predicate set to this request the data is loaded fine therefore I think the predicate is somehow used wrong by me. What am I doing wrong here?

Upvotes: 2

Views: 3909

Answers (1)

Geekswordsman
Geekswordsman

Reputation: 1307

Your thinking is correct. Change this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(blz == '%@')", blz];

to:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"blz == %@", blz];

With NSPredicate you do not use single quotes around string parameters; predicateWithFormat handles this automatically.

The parentheses are fine, but unless you're doing predicate logic that requires them, best to leave them out and keep the predicate as simple as possible.

Upvotes: 7

Related Questions