0

I created a method to search for people in an address book, and I want to return the result as an array, and if there are result to print them out, else to print "Not found".

From some reason I can print the result if the array is not nil, but the else is not working...it's not even giving me eror, this is the code:

main.m

NSMutableArray *result = [[NSMutableArray alloc] init];

        result = [myBook searchName:@"jack"];

        if (result != nil){
            for (AddressCards *nextCard in result)
            NSLog(@"%@          %@", nextCard.name, nextCard.email);
        }

        else
            NSLog(@"Not found");

AdressBook.m

-(NSMutableArray *) searchName:(NSString *) someName{

    NSMutableArray *namsFound = [[NSMutableArray alloc] init];

    for (AddressCards *addressCard in book){

        if ([addressCard.name rangeOfString:someName options:NSCaseInsensitiveSearch].location != NSNotFound)
            [namsFound addObject:addressCard];
    }

    return namsFound;
}

Thank you

1
  • NSPredicate would be a better way to search. Commented Mar 5, 2013 at 2:41

4 Answers 4

2

Your searchName: method never returns nil. It returns an empty array sometimes, but that's not the same thing.

You might do something like this in searchName::

return [namsFound count]? namsFound : nil;

This will return namsFound iff namsFound has 1 or more elements (in other words, if some names are found). Otherwise, it will return nil.

Sign up to request clarification or add additional context in comments.

1 Comment

I think this is the most elegant way to do it. And after doing this, you can just use if (result) {... in your main.m.
0

If you change this:

if (result != nil){

To this, it should work:

if (result.count) {

You are always returning a non-nil pointer, since you always alloc/init the array in the search method.

Comments

0

Instead of if (result != nil){, use if (result.count > 0){

Comments

0

It does not print "Not found" because it is never not nil. Results are always != nil because even in the case of not having found the search name, it will return an array - an unpopulated array, that is one with zero elements. if (result.count){ is the most elegant solution IMO because 0 is equivalent to boolean false, so a result.count that returns 0 will go straight to else.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.