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

前端 未结 4 1009
独厮守ぢ
独厮守ぢ 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 15:00

    If you're just trying to call the method, you could use the standard syntax:

    [self meth2:next_int];
    

    If you really need to use the performSelectorOnMainThread: you could wrap the number in an NSNumber for the call. You say you can't do this because you need to change the number, but you can just pull an int out and change that:

    [self performSelectorOnMainThread:@selector(meth2:) withObject:[NSNumber numberWithInt:next_int] waitUntilDone:NO];
    // ... later ...
    - (void)meth2:(NSNumber *)number {
      int myInt = [number intValue];
      // do stuff with myInt
    }
    

    But maybe you mean that you want to get the value of the number as an output from your call to meth2. If that's what you mean, then you could pass in a double pointer so you can receive a new object back:

    - (void)meth2:(NSNumber **)number {
      int myInt = [*number intValue];
      // do stuff with myInt
      *number = [NSNumber numberWithInt:myInt];
    }
    // The caller can now operate like this:
    NSNumber *number = [NSNumber numberWithInt:next_int];
    [self performSelectorOnMainThread:@selector(meth2:) withObject:&number waitUntilDone:YES];
    int returnInt = [*number intValue];
    

    Of course, that's not really thread-safe, so if you're doing stuff with multiple threads, I would advise using the @synchronized keyword for access to multi-thread-accessed variables, or setting up atomic properties (i.e. properties not declared as nonatomic).

    Also, meth is bad for you!! haha

提交回复
热议问题