Pass struct to performSelector:withObject:afterDelay:
I have a struct Position, like this:
typedef struct Position { int x, y; } Position;
How may I pass it in NSObject performSelector:withObject:afterDelay:
? Like this:
开发者_如何学JAVAPosition pos;
pos.x = pos.y = 1;
[self performSelector:@selector(foo:)
withObject:pos // ERROR
afterDelay:5.0f];
EDIT: changed code to fix typo
Uhm.. use a CGPoint and something like
[self performSelector:@selector(foo:)
withObject:[NSValue valueWithCGPoint:CGPointMake(pos.x, pos.y)]
afterDelay:5.0f];
And read it again as
NSValue v;
CGPoint point = [v CGPointValue];
or leave the Position class away completely, CGPoint does the same
You could wrap your custom type using NSValue
class. The error is that you didn't provide an object reference to the method.
Try using NSValue
's +(NSValue *)valueWithBytes:(const void *)value objCType:(const char *)type;
class method. On the other side you can retrieve the value using -(void)getValue:(void *)buffer;
.
preformSelector:withObject:
accepts only objects as parameters, hence you'll have to implement your foo:
method to accept an object. There are two ways to pass the struct as an object:
- create a struct-like object or
- wrap it into NSValue and unwrap it in the method.
Full answer, based on user756245's (which doesn't tell you how to use it, not a great deal of help). Also, Apple suggests you use a slightly different method these days, IIRC:
typedef myStruct { int a; } myStruct;
myStruct aLocalPointer = ... assign to it
[self performSelector:@selector(myOtherMethod:) withObject:[NSValue value:&aLocalPointer withObjCType:@encode(myStruct)] afterDelay:0.25];
This is most likely asking for trouble, but you can pass CGPoint
as id
by bridging it in this way:
withObject:(__bridge id)((void *)(&point))
This will lead to a crash if point
goes out of scope and your selector tries to read it, though.
精彩评论