开发者

Correct way to handle passing simple data into 'withObject' calls

When using objective-c there are many different ways you can stumble across something tha开发者_JAVA百科t 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜