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
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With