I downloaded a code to test whether an nsobject is empty or not
The test is something like this:
-(BOOL) isNotEmpty
{
return !(self == nil
|| [self isKindOfClass:[NSNull class]]
|| ([self respondsToSelector:@selector(length)]
&& [(NSData *)self length] == 0)
|| ([self respondsToSelector:@selector(count)]
&& [(NSArray *)self count] == 0));
};
This part puzzles me:
(NSData *)self length
How can the author just typecast NSData from NSObject like that?
The Objective-C runtime doesn’t really care what the actual type of the object it, it’s going to send it the message anyway (though of course if the object doesn’t respond to it, things will go poorly). The compiler sees “oh, NSArray responds to count, they claim this is an NSArray, and they’re sending -count, so this must be ok!”.
That said, this is pretty gross, and casting to (id) instead of (NSArray *) after checking respondsToSelector: is a much clearer way to say “we don’t know what this is, other than that it implements this method”.