Int or NSInteger as object for method argument. Objective-C

前端 未结 4 989
独厮守ぢ
独厮守ぢ 2021-02-07 14:21

I\'m having some trouble passing a number as an argument for a method:

- (void)meth2:(int)next_int;

And to call that method I need this:

<
4条回答
  •  隐瞒了意图╮
    2021-02-07 14:50

    It's a bit of a hack, but this works under ARC:

    int next_int = 1;
    [self performSelectorOnMainThread:@selector(meth2:) 
                           withObject:(__bridge id)(void*)next_int 
                        waitUntilDone:NO];
    

    The __bridge keyword will tell the compiler to ignore reference counting under ARC, but it requires a pointer, so you first have to cast the int to a C style void pointer. When your method receives the message it will treat that object pointer as if it's an integer.

    Note: If you can change the method to take an NSNumber instead of an integer, then that would be the "proper" fix. Unfortunately that's not always possible.

提交回复
热议问题