views:

48

answers:

1

I have an NSArray which holds Foo objects defined like so:

@interface Foo : NSObject <NSCopying> {
    NSString *name;
}
@property (nonatomic, retain) NSString *name;
@end

and the query:

NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", filterString];
//NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", filterString];
filteredArray = [[originalArray filteredArrayUsingPredicate:filterPredicate] mutableCopy];

and this is not working. I always get 0 results.

So, my question is:

Should I always use NSPredicate for searching only NSDictionary objects with a certain key or can I use it for searching any object as long as there is a property/method that matches the query (in this case: name)?

Thanks in advance

+2  A: 

Your code is correct. I tried it:

@interface Foo : NSObject

@property (nonatomic, retain) NSString * name;

@end
@implementation Foo

@synthesize name;

@end

NSMutableArray * a = [NSMutableArray array];
for (int i = 0; i < 100; ++i) {
    Foo * f = [[Foo alloc] init];
    [f setName:[NSString stringWithFormat:@"%d", i]];
    [a addObject:f];
    [f release];
}

NSPredicate * p = [NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", @"1"];
NSArray * filtered = [a filteredArrayUsingPredicate:p];
NSLog(@"%@", [filtered valueForKey:@"name"]);

Logs:

2010-10-29 10:51:22.103 EmptyFoundation[49934:a0f] (
    1,
    10,
    11,
    12,
    13,
    14,
    15,
    16,
    17,
    18,
    19
)

Which leads me to ask: Is your originalArray empty?

Dave DeLong
..... Or `nil`?
Peter Hosey
Or `nil`.... :)
Dave DeLong
thanks, indeed it seems correct, I realized that my error was somewhere else. ;(
nacho4d