使用 PyObjC 访问 iPhone 加速计
我想通过 PyObjC 访问 iPhone 的加速计。 这是我的代码:
@objc.signature("v@:@@")
def accelerometer_didAccelerate_(self, accelerometer, acceleration):
msgBox = UIAlertView.alloc().initWithTitle_message_delegate_cancelButtonTitle_otherButtonTitles_("Acceleration", str(acceleration.x), self, "OK", None)
msgBox.show()
msgBox.release()
@objc.signature("v@:@")
def applicationDidFinishLaunching_(self, unused):
self.accelerometer = UIAccelerometer.sharedAccelerometer()
self.accelerometer.setUpdateInterval_(1)
self.accelerometer.setDelegate_(self)
#...
问题是 str(accelleration.x) 返回 "
。我能做些什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
UIAcceleration
的x
值在 Objective-C 中定义为 属性,并在 Python 中访问acceleration.x
为您提供方法 名为“x”,而不是您可能期望的名为“x”的属性 (ivar)。你需要说:它使用 PyObjC 的“神奇”访问器机制来获取你想要的属性。
原因是:
Python 类命名空间的工作方式是,不能有同名的方法和属性。这与 Objective-C 形成鲜明对比,在 Objective-C 中,getter 方法通常与其访问的属性具有相同的名称。
这种差异可能会导致与 Objective-C 2.0 的属性功能产生一些混淆,特别是因为两种语言之间的语法看起来相同。在 Objective-C 中,您可以编写:
它会自动使用正确的 setter 或 getter 方法(
-bar
和-setBar:
)。由于 Python 的类命名空间规则,PyObjC 无法完全执行 Objective-C 代码将执行的操作,并且必须仅选择一个事物(方法或属性)来由名称 foo.bar 表示。 >;它选择的是方法。A
UIAcceleration
'sx
-value is defined in Objective-C as a property, and accessingacceleration.x
in Python gives you the method named 'x', not the attribute (ivar) named 'x' as you might expect. You need to say:which uses PyObjC's "magic" accessor mechanism to get the attribute you want.
The reasons for this:
The way Python's class namespaces work, you can't have a method and an attribute with the same name. This is in contrast to Objective-C where a getter method often has the same name as the attribute it accesses.
This difference can cause a little confusion with Objective-C 2.0's properties feature, especially since the syntax looks identical between the two languages. In Objective-C, you write:
Which automatically uses the proper setter or getter methods (
-bar
and-setBar:
). PyObjC, because of Python's class namespace rule, can't do exactly what the Objective-C code would do, and has to pick just one thing (method or attribute) to be represented by the namefoo.bar
; the thing it chooses is the method.