最近的ly, I was working on aPyObjCproject and I ran into a slightly complex situation. I wanted to schedule an action and run it at a later time, unless a specific condition was satisfied, in which case I wanted to invalidate the scheduled action.
但我的思绪在目标-C模式下滚动，所以我立即通过使用NSTimer. The definition of the
NSTimermethod for creating a new instance looks like this1:
No problem, we can just translate that using our handy PyObjC rules.
Most of the arguments are self explanatory, but there was something I was unsure of: how do you create selectors in PyObjC? It turns out, pretty easily, but with a bit of magic.
def reset_timer(self): if self.timer is not None: self.timer.invalidate() s = objc.selector(self.advertise,signature='v@:') self.timer = NSTimer.scheduleTimerWithTimeInterval_target_selector_userInfo_repeats(30.0,self,s,None,True) def advertise(self): print "Don'cha wanna buy something?" def vend(self): self.reset_timer() print "Thanks for buying."
So that all makes sense, right? Except, perhaps, for one little thing that doesn't make any sense at all? If I may be so bold, the
signature='v@:'part seems the slightest bit magical and even (dare I say) arbitrary. Fortunately, it's an easy magic trick to pick up.
vindicates that the method will return void--i.e. it doesn't return anything, and the second part,
@：, indicates that it is an instance method. Since my object isn't taking any parameters thats all there is to it.
But if the method was taking some parameters, thats easy too. The signature
v @：@ fi表示该方法需要三个签名。
irepresents an integer. You can also use those same symbols instead of
vfor specifying the type of a returned object. For example, consider this Python method:
Awkward, to be sure, but nothing insurmountable with our four magic symbols:
The places I scrounged for information--all of which were helpful but not quite comprehensive--wereobjc.selector and objc.signature at Jim Matthews Blog,一些蟒蛇文档在线, and the always helpful Python docstrings in the PyObjC code itself:
>>>进口objc>>>打印objc.选择器.__doc__选择器(function, [, selector] [, signature] [, isClassMethod=0][, returnType] [, argumentTypes] [, isRequired=True]) -> selector
从函数返回目标-C方法。另一个论点specify attributes of the Objective-C method.etc…