tags:

views:

40

answers:

1

I have 2 objects, AddressBook and AddressCard. The AddressCard has the properties name, email, & birthday. The AddressBook has a lookup method that takes a string as an argument, and searches each added AddressCard for a match. In this lookup method I'd like to have an NSArray of each of the fields i'd like to search in the AddressCards. Then loop through each AddressBook entry test each field in my array for a match to the lookup's argument. The problem is I dont know how to access an objects property dynamically with a string - is this possible in Objective-C, or should I be trying to do this in a different way? I realize I could just use IF statements, but thats not a scalable solution.

Heres my lookup method:

-(AddressCard *)lookup:(NSString *)aName
{
    NSArray *fields = [[NSArray alloc] initWithObjects:@"name",@"email",@"birthday",nil];
    BOOL STATUS = NO;
    for(AddressCard *entry in book)
    {

        for(int i = 0; i < [fields count]; i++)
        {
            NSString *fieldName = [[NSString alloc] initWithString:[fields objectAtIndex:i]];
            NSRange range = [[entry fieldName]  rangeOfString:aName];

            if(range.location != NSNotFound)//Important to not directly test the NSRange struct, but one of its properties(BAD_ACCESS)
            {
                NSLog(@"'%@' found in field:%@ at range:%i,%i",aName,fieldName,range.location,range.length);
                STATUS = YES;
                return entry;
            }
            [n release];
        }

    }
    if(!STATUS)
        NSLog(@"'%@' not found in %@ address book",aName, bookName);

    return nil;
}

Any ideas or suggestions appreciated, thanks!

+3  A: 

The method you are looking for is valueForKey:

NSRange range = [[entry valueForKey:fieldName]  rangeOfString:aName];
Aleph
entry is the AddressCard object returned from enumerating through the array of AddressCards and doesnt have the valueForKey method?
philip
as long as AddressCard inherits from NSObject and you declare your properties with @property, you get that for free (http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/BasicPrinciples.html#//apple_ref/doc/uid/20002170-BAJEAIEE)
Aleph
Thank you for that -- now I have a new problem though, I'm getting this error:NSUnknownKeyException', reason: '[<AddressCard 0x100108dd0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key birthday. I'm going to google this but I've never gotten that error..
philip
I did print out the fields array and it does contain the strings which correspond to properties on the AddressCard class that were created with @property and @synthesize.
philip
thanks - found the problem - birthday property is actually birthdate. *palmface.
philip