Sunday, March 13, 2011

NSPredicate: PyObjC version

Here is the answer in the previous post, converted to PyObjC. It's a bit simpler, except that some of the methods require a "real" NSArray or NSString.


from Foundation import *
import objc

class NSString(objc.Category(NSString)):
def validate(self):
A = self.UTF8String().split(':')
fm = NSFileManager.defaultManager()
def f(s):
print 'test', s
home = NSHomeDirectory()
s = s.replace('~',home)
return fm.fileExistsAtPath_(s)
return all([f(s) for s in A])

s = NSString.stringWithString_('~/Desktop')
print s.validate()

for s in ['~:~/Desktop','xyz']:
s = NSString.stringWithString_(s)
f = NSExpression.expressionForConstantValue_(s)
e = NSExpression.expressionForFunction_selectorName_arguments_(
f,'validate',None)
results = e.expressionValueWithObject_context_(None,None)
print results
print

p = NSPredicate.predicateWithFormat_(
"FUNCTION(SELF, 'validate') isEqual:YES")
A = ['~/Desktop','xyz']
A = [NSString.stringWithString_(s) for s in A]
A = NSArray.arrayWithArray_(A)
for item in A.filteredArrayUsingPredicate_(p):
print item

print p.evaluateWithObject_(NSString.stringWithString_('~/Desktop'))


output:


test ~/Desktop
True
test ~
test ~/Desktop
True
test xyz
False

test ~/Desktop
test xyz
~/Desktop
test ~/Desktop
True