views:

62

answers:

2

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.

+4  A: 

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];
   ...
KennyTM
This is surely the other option but then I can use on ObjC object straight away and change my function to accept an object. I wanted to use the struct to avoid define an additional object.
georgij
+3  A: 

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.

bbum