Re: Searching array with block
Re: Searching array with block
- Subject: Re: Searching array with block
- From: Quincey Morris <email@hidden>
- Date: Sun, 11 Nov 2012 15:01:47 -0800
On Nov 11, 2012, at 14:30 , Erik Stainsby <email@hidden> wrote:
> - (IBAction) updateIncrementalSearch:(id)sender {
>
> NSString * term = [sender stringValue];
> if(term) {
> NSMutableArray * matchResults = [NSMutableArray new];
>
> NSUInteger index = [[self content] indexOfObjectPassingTest:^(RSPerson * rsp, NSUInteger idx, BOOL *stop) {
> if([[rsp firstName] caseInsensitiveCompare:term] == NSOrderedSame) {
If rsp.firstName happens to be nil, then sending it any message (such as 'caseInsensitiveCompare:') will return 0, and NSOrderedSame is 0 too. So you'll get an unwanted match. Since you're certain that 'term' is non-nil, try sending the compare to it instead.
> // *stop = YES;
> [matchResults addObject:rsp];
> return YES;
> }
> else {
> return NO;
> }
> }];
>
> #pragma unused(index)
>
> if([matchResults count]){
> self.matches = [NSArray arrayWithArray:matchResults];
(This line has quite a big code smell. Perhaps "matches" should really be an array-valued simple property as this code suggests, but it's far more usual to have an indexed property backed by an array variable. In the latter case, arbitrarily assigning a different array is perilous.)
> // throw a notification
> }
> else {
> NSLog(@" [d] %s %@",__LINE__,__PRETTY_FUNCTION__, @"no match found");
> }
>
> for(RSPerson * p in self.matches) {
> NSLog(@" [d] %s %@",__LINE__,__PRETTY_FUNCTION__, p.firstName);
> }
> }
> }
>
>
> This consistently reports
> 2012-11-11 14:20:14.050 SearchController[30109:303] [0105] -[RSSearchController updateIncrementalSearch:] (null)
Your log proves that there is an object whose "firstName" is nil -- the for loop will never execute with a nil value for p, so it must be p.firstName that's nil. Probably this is the very first element of your content array.
> in spite of having 51 records which have firstName values… And regardless of the number of matches which it ought to be generating it returns exactly one result each time.
You're using 'indexOfObject…' which only finds one object. If you want more, than use an 'indexesOfObjects…" method.
> (And btw, is it legit to NSLog() from inside a block ?)
Yup.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden