开发者

Objective-C: Result of casting id to BOOL?

Does the following function return YES if object != nil?

- (BOOL)boolForObject:(id)object {
    return (BOOL)object;
}

I've tested with object = [[NSObject alloc] init] but got mix开发者_如何学Ced results.


A pointer is larger than a BOOL, so when you cast it will truncate and take only the 8 least significant bits of the pointer and make it a BOOL. If those bits all happen to be zero then that is equivalent to NO.

So to answer your question, no it does not (well sometimes it will depending on the pointer value)

Here's an example with using Xcode 5.1.1 on 32 bit architecture:

void* p = (void*)0xfeeeff00;
BOOL  b = (BOOL)p;

NSLog(@"p=%08x (%lu), b=%08x (%lu)", (uint32_t)p, sizeof p, (uint32_t)b, sizeof b);

It prints out:

p=feeeff00 (4), b=00000000 (1)


What is the actual purpose of your method?

If it's just to check whether an object is nil or not, why not do it like this:

- (BOOL)boolForObject:(id)object 
{
    return (object != nil);
}

It's more obvious what the result will be.


You could also do:

return !!object;


I don't think so, but

return object != nil;

will.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜