您的位置:首页 > 编程语言

方便实现逻辑功能的代码

2011-10-04 23:01 260 查看
通常我们可以使用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, 你可以在这里下载到这个代码。

http://www.cocoachina.com/b/?p=217#more-217
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: