I would like to execute a function which obtains a struct in an separate Thread but not sure how to pass the struct right.
Having this:
- (void) workOnSomeData:(struct MyData *)data;
How to properly call:
struct MyData data = ... ;
[[[NSThread alloc] initWithTarget:self selector:@selector(workOnSomeData:) object: ...
Using &data
does not work.
The object
must be an ObjC object. A struct is not.
You can create an ObjC to hold these info:
@interface MyData : NSObject {
...
or encode the struct in an NSData, assuming it does not contain any pointers:
NSData* objData = [NSData dataWithBytes:&data length:sizeof(data)];
...
-(void)workOnSomeData:(NSData*)objData {
struct MyData* data = [objData bytes];
...
While kennytm's answer is correct, there is a simpler way.
Use NSValue's +valueWithPointer: method to encapsulate the pointer in ani object for the purposes of spinning off the thread. NSValue does no automatic memory management on the pointer-- it really is juste an opaque object wrapper for pointer values.
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