Here's the code:
for(int i = 0; i < personListViewController.peopleCount; i++) {
[NSThread detachNewThreadSelector:@selector(getPerson:) toTarget:self withObject:i];
}
getPerson looks like this:
- (void)getPerson:(int)whichPerson { }
When I build this, I get the following :warning: passing argument 3 of 'detachNewThreadSelector:toTarget:withObject:' makes pointer from integer without a cast
All I want to do is pass an int to getPerson via detachNewThreadSelector and I can't figure out how the heck to get it to take anything but an object pointer. What am I missing here?
The selector you pass as the first argument to -[NSThread detachNewThreadSelector:toTarget:withObject:]
must take a single argument which is of type id
(a pointer to an object instance). Although you can play games with the fact that (on most platforms), a pointer is the same size as an int
and type cast your value into an id
and then back to an int
, you should not rely on this behavior. Instead, write a wrapper method that takes an NSNumber
argument and wrap your int
in an NSNumber
. The wrapper method implementation could be:
- (void)getPersonWithNumber:(NSNumber*)number {
[self getPerson:[number integerValue]];
}
Your loop would then be
for(NSInteger i = 0; i < personListViewController.peopleCount; i++) {
[NSThread detachNewThreadSelector:@selector(getPersonWithNumber:) toTarget:self withObject:[NSNumber numberWithInteger:i];
}
Note that I've converted from int
to NSInteger
throughout. Unless you are interfacing with legacy code that uses int
, you should use NSInteger
which is a typedef for the appropriate size integer on each platform (32 or 64-bit) in new Cocoa code.
You need to wrap the integer in an NSNumber class, to make the number an object.
[NSThread detachNewThreadSelector:@selector(getPerson:) toTarget:self withObject:[NSNumber numberWithInteger:i]];
NSThread doesn't take primitives (like int or char), so you have to use NSNumber!
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With