How to create a method to return an array with object of another class?
I have a class of AddressCards.h/m
, and another class of AddressBook
,now I want to create a search method to look for names in the AddressBook class but getting some error.
I think I need my method to return an AddressCards type pointer but I'm not sure how to return it, since I need to have an array holding the names in case there is more than 1 match..
This is my current code:
-(NSMutableArray *) searchName:(NSString *) someName{
NSMutableArray *results = [NSMutableArray alloc];
for (NSString *name in book)
{
if ([someName caseInsensitiveCompare:name] == NSOrderedSame)
[results addObject:name];
}
return results;
}
@end
I'm getting error in this line: if ([someName caseInsensitiveCompare:name] == NSOrderedSame)
That says signal 1 SIGABRT
which I have no idea what is it :/
this is the method that adds addresscards:
-(void) addCard:(AddressCards *)theCard{
[book addObject:theCard];
}
book
is an NSMutableArray of AddressCards
, however you are trying to iterate over the objects using an NSString ( name
).
You should iterate using addressCards
object and then make the comparison using the corresponding name
property. I believe you should implement the searching method similar to the code below:
-(NSMutableArray *) searchName:(NSString *) someName{
NSMutableArray *results = [[NSMutableArray alloc] init];
for (AddressCards *addressCard in book)
{
// do your comparison check here
// assuming that you have a name property in AddressCards class
if ([addressCard.name rangeOfString:someName].location != NSNotFound)
[results addObject:addressCard.name];
}
return results;
}
Hope this helps.
Edit: Modified the comparison code as desired using this answer.
One problem is that you haven't called init
when creating your results
array.
NSMutableArray *results = [NSMutableArray alloc];
should be:
NSMutableArray *results = [[NSMutableArray alloc]init];
This will definitely cause a SIGABRT
error.
上一篇: 比较两个字符串?