1

I want to pass an NSInteger argument to a method called using performSelector:WithObject:afterDelay, so I have this code:

   id arg = [NSNumber numberWithInt:myIdentifier]; 
   [self performSelector:@selector(myMethod:) withObject:arg afterDelay:kDuration];


    - (void) myMethod: (id) identifier
    {
    ...
    }

Within myMethod:, how do I convert the identifier from an id to an NSInteger?

I've seen this previous question: SEL performSelector and arguments

but I don't understand myMethodForNumber: - how is that used to unbox the number?

Community
  • 1
  • 1
Gruntcakes
  • 37,738
  • 44
  • 184
  • 378

3 Answers3

2

myMethod can accept the NSNumber as the parameter. You can then get the integer value by using the NSNumber instance method.

- (void)myMethod:(NSNumber *)number {
    NSInteger value = [number integerValue];
}
Ian L
  • 5,553
  • 1
  • 22
  • 37
1

Update: refer to the question, please

Reading or writing with performSelector: is as following,

@import os.log;

- (void)testSEL
{
    os_log(OS_LOG_DEFAULT, "Original NSObject.version is %zd", NSObject.version); // original 0
    NSObject.version = 1;
    os_log(OS_LOG_DEFAULT, "Custom NSObject.version is %zd (should be 1)", NSObject.version); // custom 1

    // Reading
    NSInteger v = (NSInteger)[NSObject performSelector:@selector(version)];
    os_log(OS_LOG_DEFAULT, "Reading: version is %zd", v);

    // Writing
    [NSObject performSelector:@selector(setVersion:) withObject:(__bridge id)(void *)2];
    os_log(OS_LOG_DEFAULT, "Writing: NSObject.version is %zd", NSObject.version);
}
DawnSong
  • 4,752
  • 2
  • 38
  • 38
0

You can just cast the value if you know its type:

- (void) myMethod: (id)identifier
{
    NSNumber *myNumber = (NSNumber *)identifier;
}

Alternatively, you can just specify the type that the method takes:

- (void) myMethod:(NSNumber *)myNumber
{
    // Use myNumber
}
Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102