Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass struct as id possible?

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.

like image 990
georgij Avatar asked Apr 12 '10 14:04

georgij


2 Answers

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];
   ...
like image 31
kennytm Avatar answered Nov 12 '22 00:11

kennytm


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.

like image 91
bbum Avatar answered Nov 12 '22 00:11

bbum