本文介绍了重用NSPredicate用于新的变量替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以重用NSPredicate作为新的变数替代品吗?我的NSPredicate是相当简单:

Can I reuse NSPredicate for new variable substitute? My NSPredicate is rather simple:

NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"id == %@",userID];

userID是在运行时生成不同的值,现在对于每个userID我需要创建一个NSPredicate。是的,我可以重用我的NSPredicate吗?

The userID is generated at run-time with different value, right now for each userID I need to create a NSPredicate. So is it possible I can reuse my NSPredicate ?

推荐答案

是的,你可以做一个变量:

Yep, you can do this with a variable:

NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"id == $user"];

将该谓词保存在某个位置,然后在需要实际开始过滤内容时执行此操作:

Save that predicate somewhere, then do this when you need to actually start filtering stuff:

NSDictionary *sub = [NSDictionary dictionaryWithObject:user forKey:@"user"];
NSPredicate *filter = [userPredicate predicateWithSubstitutionVariables:sub];

这是一种更有效的重用谓词的方法,因为解析格式字符串相当昂贵)只发生一次。

This is a much more efficient way to reuse a predicate, because parsing the format string (which can be pretty expensive) only happens once.

这篇关于重用NSPredicate用于新的变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 03:04