Supposing we have:
id value = [self valueForKey:@"frame"];
BOOL valueIsCGRect = ???;
How can I decide? Should I cast id to something?
Supposing we have:
id value = [self valueForKey:@"frame"];
BOOL valueIsCGRect = ???;
How can I decide? Should I cast id to something?
With a bit more context and some typecasting:
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));
}
}
CGRect
is a struct
, not an Objective-C object, so if you have an id
, you don't have a CGRect
.
What you probably have is an NSValue
wrapping a CGRect
. You can get the CGRect
out using [value CGRectValue]
.
frame
should certainly return a (wrapped) CGRect
, but if you really need to check and make sure, you can use JustSid's answer.
The returned value will be of type
NSValue
for scalar types, which provides the methodobjCType
, which returns the encoded type of the wrapped scalar type. You can use@encode()
to get the encoding for an arbitrary type, and then compare theobjCType
.