Why would passing an unsigned int to execute a Selector lose bits?

I am trying to pass a hex value as an unsigned int to a method using a dynamic link. The value that I pass as a parameter is somehow distorted. What's happening?

- (void)callPerformSelector
{
    NSNumber *argument = [NSNumber numberWithUnsignedInt:(unsigned int)0xFFFFFFFF];
    SEL selector = NSSelectorFromString(@"testPerformSelector:");
    NSLog(@"testPerformSelector object %@", argument);
   [self performSelector:selector withObject:argument];
}

- (void)testPerformSelector:(unsigned int) arg1
{
    NSLog(@"testPerformSelector unsigned int %u", arg1);
    NSLog(@"testPerformSelector hex %X", arg1);
}

Output:

testPerformSelector object 4294967295
testPerformSelector unsigned int 4294967283
testPerformSelector hex FFFFFFF3
+4
source share
3 answers

Because it should be:

- (void)callPerformSelector
{
    NSNumber *argument = @0xFFFFFFFF;
    SEL selector = @selector(testPerformSelector:);
    NSLog(@"testPerformSelector object %@", argument);
   [self performSelector:selector withObject:argument];
}

- (void)testPerformSelector:(NSNumber *) arg1
{
    NSLog(@"testPerformSelector unsigned int %u", arg1.unsignedIntValue);
}

unsigned intand NSNumber *- two different things

+5
source

There is an easy reason and a complex reason.

Simple reason: why this does not work. The first argument to the target performSelectorWithObjectmust be an object. You point to an unsigned integer in your function signature, and then pass an object ( NSNumber) when you call it. Therefore, instead of:

- (void)testPerformSelector:(unsigned int) arg1

you should have

- (void)testPerformSelector:(NSNumber *) arg1

NSNumber unsignedIntValue, 0xFFFFFFFF .

: , . NSNumber - , , . NSNumber , , objective-c , , NSNumber , "" , , ( ) . Q & A.

+2

, , :

- (void)testPerformSelector:(NSNumber *) arg1
{
    NSLog(@"testPerformSelector hex %x", [arg1 unsignedIntValue]);
}

Update: as pointed out by @ gnasher729, the reason why the passed number looks like -13is because it is a marked pointer .

+1
source

Source: https://habr.com/ru/post/1660299/


All Articles