Is it better to check the class of an object before casting?

Should I just specify a variable or use isKindOfClass: to check it and then quit? Which one will be better and more efficient? (Well, efficiency is not a problem just for a bit.) I want the string below to be NSString .

Example:

 NSString *string = (NSString *)result; 

or

 if(![string isKindOfClass:[NSString class]] { //cast it } 
+4
source share
2 answers

Although simple casting will be more efficient, it might be better for your application if you first check if the result is what you think.

It all depends on how safe you want to be.

+3
source

Casting has no runtime effect. This is just a message to the compiler that you are sure that it can be assigned from one type to another (it will also turn off warnings that โ€œmay not respondโ€ when you have an id ).

 NSString * s = (NSString *)[NSNumber numberWithInt:0]; // The compiler will let you do this, but it 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 other hand, isKindOfClass: does not affect compilation time; it is sent, like any other message, at runtime, and its result is then determined.

Iโ€™m not sure what you are trying to achieve, but I canโ€™t come up with anything useful that could be done by combining these two mechanisms.

There is no reason to send isKindOfClass: before casting, but not for the reasons you think. Either you know the class at compile time, and in this case isKindOfClass: pointless or not, in which case casting is inefficient.

+5
source

Source: https://habr.com/ru/post/1392812/


All Articles