Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it best to check an object's class before casting?

Should I just cast a variable, or use isKindOfClass: to check it and then cast? Which one will be better and more efficient? (Well, efficiency isn't an issue just for a little bit.) I want string below to be an NSString.

Example:

NSString *string = (NSString *)result;

or:

if(![string isKindOfClass:[NSString class]]
{
   //cast it
} 
like image 478
TeaCupApp Avatar asked Jan 24 '12 23:01

TeaCupApp


2 Answers

Casting doesn't have any runtime effect. It's only a message to the compiler that you're sure it's okay to assign from one type to another (it'll also silence warnings about "may not respond to" when you've got an id).

NSString * s = (NSString *)[NSNumber numberWithInt:0];
// The compiler will let you do this, but it's pointless, because:
[s floatValue];    // Okay; NSNumber also implements -floatValue
[s lowercaseString];    // Crashes; s is still an NSNumber instance, 
                        // which doesn't respond to -lowercaseString

On the flip side, isKindOfClass: doesn't have any effect at compile time; it's sent, just like any other message, at runtime, and its result is determined then.

I'm not sure what you're trying to achieve, but I can't think of anything useful that can done by combining these two mechanisms.

There's no reason to send isKindOfClass: before casting, but not for the reasons you think. Either you know the class at compile time, in which case isKindOfClass: is pointless, or you don't, in which case casting is ineffectual.

like image 87
jscs Avatar answered Sep 22 '22 18:09

jscs


Although just casting would be more efficient it may be better for your app if you first check if the result is what you think it is.

It all depends on how safe you want to be

like image 33
arclight Avatar answered Sep 20 '22 18:09

arclight