将选择器与 NSPredicate 一起使用

发布于 2024-09-09 04:06:58 字数 612 浏览 5 评论 0 原文

我有一个包含几个不同 NSString 的对象。显示此对象时,根据对象的另一属性,我将显示一个字符串或另一个字符串。我在对象中定义了一个函数,负责决定要显示哪个字符串。因此,作为一个简单的示例:

@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;
    }
}

现在,我想创建一个 NSPredicate 来搜索这些对象的数组。是否可以创建一个对 getDisplayString 结果进行搜索的系统?显然,我可能可以在谓词中复制 getDisplayString 的行为,但随后我将在逻辑上加倍,并且可能会导致某个地方出现错误。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赠我空喜 2024-09-16 04:06:58

是的。

NSPredicate *p = [NSPredicate predicateWithFormat:@"getDisplayString = %@", @"foo"];
NSArray *filtered = [arrayOfMyObjects filteredArrayUsingPredicate:p];

附带说明一下,除非您要通过 out 参数通过 byref 返回值,否则不应在方法名称前添加 get 前缀。查看文档了解更多信息。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文