尝试将CGrect传递给performSelector withObject

时间:2010-02-20 13:59:21

标签: iphone cocoa-touch selector argument-passing

我正在尝试传递CGRect:

SEL frameSel = NSSelectorFromString(@"setFrame:");
CGRect rect = CGRectMake(10, 10, 200, 100);
[object performSelector:frameSel withObject:rect ];

但这不编译

我也尝试过:

SEL frameSel = NSSelectorFromString(@"setFrame:");
CGRect rect = CGRectMake(10, 10, 200, 100);
NSValue * value = [NSValue valueWithCGRect:rect];
[object performSelector:frameSel withObject:value ];

实际上,这确实可以编译,但是当我调试时,框架没有正确设置:

po object
<UILabel: 0x39220f0; frame = (0 0; 200 100); text = 'reflectionLabel'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x3922240>>

但它应该是frame =(10 10; 200 100)

我该如何解决这个问题?

提前谢谢!

2 个答案:

答案 0 :(得分:5)

CGRect rect = CGRectMake(10, 10, 200, 100);
[object performSelector:frameSel withObject:rect ];
     

但这不编译

正确,因为rect是一个结构,而不是指向对象的指针。

CGRect rect = CGRectMake(10, 10, 200, 100);
NSValue * value = [NSValue valueWithCGRect:rect];
[object performSelector:frameSel withObject:value ];
     

实际上,这确实可以编译,但是当我调试时,框架没有正确设置:

po object
<UILabel: 0x39220f0; frame = (0 0; 200 100); text = 'reflectionLabel'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x3922240>>

嗯,这不是垃圾,所以看起来它有效,即使原点在某种程度上保持为零。你可能想问一个单独的问题。

无论如何,你为什么要使用performSelector:withObject:?你没有把它解决到一个特定的线程,你没有把它延迟;为什么不简单地说object.frame = rect

答案 1 :(得分:5)

您必须使用NSInvocation来处理任何非id参数或返回值:

CGRect rect = CGRectMake(104, 300, 105, 106);
UIView *view = [[UIView alloc] init];

NSMethodSignature *methodSig = [view methodSignatureForSelector:@selector(setFrame:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
invocation.target = view;
invocation.selector = @selector(setFrame:);
[invocation setArgument:&rect atIndex:2];
[invocation invoke];