I have an object which contains several different NSStrings. When displaying this object, depending on another attribute of the object, I will display one string or another. I have a function defined in the object that takes care of deciding which string to display. So, as a simple example:
@interface MyObject : NSObject {
NSString* string1;
NSString* string2;
NSString* string3;
int stringNum;
}
-(NSString)getDisplayString {
if(stringNum == 1) {
return string1;
} else if (stringNum == 2) {
return string2;
} else if (stringNum == 3) {
return string3;
}
}
Now开发者_开发技巧, I would like to create an NSPredicate
for searching an array of these objects. Is it possible to create one that will search on the results of getDisplayString
? Obviously I could probably replicate the behaviour of getDisplayString
within the predicate, but then I'll be doubling up on logic, and probably lead to an error somewhere down the line.
Yes.
NSPredicate *p = [NSPredicate predicateWithFormat:@"getDisplayString = %@", @"foo"];
NSArray *filtered = [arrayOfMyObjects filteredArrayUsingPredicate:p];
As a side note, you shouldn't prefix a method name with get
unless you're going to be returning a value byref via an out parameter. Check out the documentation for more info.
精彩评论