Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C Threading Question

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?

like image 377
lewsid Avatar asked Dec 06 '22 05:12

lewsid


2 Answers

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.

like image 111
Barry Wark Avatar answered Dec 18 '22 03:12

Barry Wark


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.

like image 34
micmoo Avatar answered Dec 18 '22 03:12

micmoo