处理将简单数据传递到“withObject”的正确方法来电

发布于 2024-11-09 05:48:01 字数 328 浏览 0 评论 0原文

使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

久光 2024-11-16 05:48:01

对于这些类型的操作,Cocoa 确实需要一个从 NSObject 派生的 Objective-C 类。要传递简单类型(例如整数、布尔值或浮点值),NSNumber 类可用于封装跨选择器调用的值。使用该类提供的实用程序方法,可以从基本类型创建 NSNumber 对象,并从该对象检索该基本类型,这非常容易:

- (void)action:(id)sender
{
    enum EnumType eVal = /* ... */;
    [self performSelectorOnMainThread:@selector(aMethod:) withObject:[NSNumber numberWithInt:(int)eVal] waitUntilDone:YES];
}

- (void)aMethod:(NSNumber)enumValue
{
    enum EnumType eVal = (EnumType)[enumValue intValue];
}

还有 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:

- (void)action:(id)sender
{
    enum EnumType eVal = /* ... */;
    [self performSelectorOnMainThread:@selector(aMethod:) withObject:[NSNumber numberWithInt:(int)eVal] waitUntilDone:YES];
}

- (void)aMethod:(NSNumber)enumValue
{
    enum EnumType eVal = (EnumType)[enumValue intValue];
}

There is also the NSValue class that can do the same for lower-level types, like pointers or byte strings.

落花随流水 2024-11-16 05:48:01

您需要将其包裹在某种物体中。无论是自定义数据对象还是简单基元,请使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文