Question

Supposing we have:

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

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

Était-ce utile?

La solution

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
}

Autres conseils

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.

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));
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top