通常我们可以使用NSPredicate来进行逻辑计算,不过一般来说代码都很长。
比如考虑,要实现如下逻辑:(A or B) but not (A and B) 需要用很长的一堆代码来实现:
-
NSPredicate *xor = [ NSCompoundPredicate andPredicateWithSubpredicates :
-
[ NSArray arrayWithObjects :
-
[ NSCompoundPredicate orPredicateWithSubpredicates :
-
[ NSArray arrayWithObjects : a, b, nil ]
-
],
-
[ NSCompoundPredicate notPredicateWithSubpredicate :
-
[ NSCompoundPredicate andPredicateWithSubpredicates :
-
[ NSArray arrayWithObjects : a, b, nil ]
-
]
-
],
-
nil
-
]
-
];
不过如果用了本文介绍的方法,就会简单地变成下面的代码:
-
NSPredicate *xor = [ [a or : b ] and : [ [a and : b ] not ] ];
同样地,你还可以使用xor运算:
-
NSPredicate *xor = [a xor : b ];
本文介绍的代码是一个Foundation Kit的NSPredicate的扩展,作者是Jonathan Grynspan, 你可以在这里下载到这个代码。