假设我们有:
id value = [self valueForKey:@"frame"];
BOOL valueIsCGRect = ???;
我该如何决定?我应该把 id 投射到什么东西上吗?
假设我们有:
id value = [self valueForKey:@"frame"];
BOOL valueIsCGRect = ???;
我该如何决定?我应该把 id 投射到什么东西上吗?
返回的值将是NSValue标量类型的类型,它提供了方法objCType,该方法返回包装的标量类型的编码类型。您可以使用@encode()获取任意类型的编码,然后比较objCType.
if(strcmp([value objCType], @encode(CGRect)) == 0)
{
// It's a CGRect
}
CGRect是一个struct,而不是一个Objective-C对象,所以如果你有一个id,你就没有一个CGRect。
您可能拥有的是一个NSValue包装 a CGRect。您可以CGRect使用[value CGRectValue].
frame当然应该返回 a (wrapped) CGRect,但如果你真的需要检查并确保,你可以使用JustSid 的 answer。
有了更多的上下文和一些类型转换:
id value = [self valueForKeyPath:keyPath];
//Core Graphics types.
if ([value isKindOfClass:[NSValue class]])
{
//CGRect.
if(strcmp([(NSValue*)value objCType], @encode(CGRect)) == 0)
{
//Get actual CGRect value.
CGRect rectValue;
[(NSValue*)value getValue:&rectValue];
NSLog(@"%@", NSStringFromCGRect(rectValue));
}
//CGPoint.
if(strcmp([(NSValue*)value objCType], @encode(CGPoint)) == 0)
{
//Get actual CGPoint value.
CGPoint pointValue;
[(NSValue*)value getValue:&pointValue];
NSLog(@"%@", NSStringFromCGPoint(pointValue));
}
}