在Objective-C中将BOOL转换为id

时间:2011-12-19 17:58:49

标签: iphone objective-c

这是我的代码:

[delegate performSelectorOnMainThread:@selector(setVariablePremierAffichage:) withObject:TRUE waitUntilDone:NO];

问题是参数“withObject”只采用“id”类型,那么,如何将我的值“TRUE”转换为id类型?我还在Xcode for iOS 5中使用ARC内存管理。

3 个答案:

答案 0 :(得分:20)

传递NSNumber。使用boolNumber = [NSNumber numberWithBool:TRUE]。您的方法应定义为:

-(void)setVariablePremierAffichage:(NSNumber *)boolNumber
{
    BOOL value = [boolNumber boolValue];
    // do something
}

答案 1 :(得分:4)

使用CFbooleanreference并将其强制转换

[delegate performSelectorOnMainThread:@selector(setVariablePremierAffichage:) withObject:(id)kCFBooleanTrue waitUntilDone:NO];

答案 2 :(得分:0)

无法将基元转换为id。如果需要动态调用方法,例如使用performSelector,则需要使用NSInvocation:

NSMethodSignature *sig = [self methodSignatureForSelector:@selector(setVariablePremierAffichage:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
BOOL yes = YES;
[invocation setArgument:&yes atIndex:2];
[invocation setTarget:self];
[invocation setSelector:@selector(setVariablePremierAffichage:)];
[invocation invoke];

干杯!