处理将简单数据传递到“withObject”的正确方法来电
使用 Objective-C 时,您可以通过多种不同的方式偶然发现使用 withObject 的东西。 PerformSelectorOnMainThread 就是一个很好的例子。
[self performSelectorOnMainThread:@selector(aSelector) withObject:anObject waitUntilDone:YES];
这将使用对象 anObject 调用选择器 aSelector。我经常发现自己的选择器采用简单的数据类型,例如 int 或 enum,并且我想将其传递给“withObject”。这样做的正确方法是什么?
When using objective-c there are many different ways you can stumble across something that would uses withObject. performSelectorOnMainThread is a good example.
[self performSelectorOnMainThread:@selector(aSelector) withObject:anObject waitUntilDone:YES];
This calls the selector aSelector with the object anObject. I often find myself with selector that takes a simple data type, like an int or an enum and I want to pass this off to a 'withObject'. What is the correct way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于这些类型的操作,Cocoa 确实需要一个从 NSObject 派生的 Objective-C 类。要传递简单类型(例如整数、布尔值或浮点值),NSNumber 类可用于封装跨选择器调用的值。使用该类提供的实用程序方法,可以从基本类型创建 NSNumber 对象,并从该对象检索该基本类型,这非常容易:
还有 NSValue 类可以对较低级别的类型执行相同的操作,例如指针或字节字符串。
For those kinds of operations, Cocoa really wants an Objective-C class that derives from NSObject. To pass simple types like an integer, bool, or float value, the NSNumber class can be used to encapsulate the value across selector call. This is pretty easy with the utility methods the class provides to both create an NSNumber object from a primitive type, and retrieving that primitive type back from the object:
There is also the NSValue class that can do the same for lower-level types, like pointers or byte strings.
您需要将其包裹在某种物体中。无论是自定义数据对象还是简单基元,请使用
NSNumber
。You'll want to wrap it in some sort of object. Either a custom data object or in the case of simple primitives, use
NSNumber
.