开发者

Pass struct as id possible?

开发者 https://www.devze.com 2022-12-26 06:56 出处:网络
I would like to execute a function which obtains a struct in an separate Thread but not sure how to pass the struct right.

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 MyDat开发者_运维知识库a data = ... ;
[[[NSThread alloc] initWithTarget:self selector:@selector(workOnSomeData:) object: ...

Using &data does not work.


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.


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];
   ...


You can pass the structure through void * like this. Tested and it worked.

struct MyData data = ... ;

[[[NSThread alloc] initWithTarget:self selector:@selector(workOnSomeData:) object:(void *)(&data)];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号