How to check if an id points to a CGRect?

1.2k views Asked by At

Supposing we have:

id value = [self valueForKey:@"frame"];
BOOL valueIsCGRect = ???;

How can I decide? Should I cast id to something?

3

There are 3 answers

7
JustSid On BEST ANSWER

The returned value will be of type NSValue for scalar types, which provides the method objCType, 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 the objCType.

if(strcmp([value objCType], @encode(CGRect)) == 0)
{
   // It's a CGRect
}
1
Geri Borbás On

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));
    }
}
3
Kevin On

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.