Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 mixed results.

like image 711
ma11hew28 Avatar asked Aug 19 '11 15:08

ma11hew28


1 Answers

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)
like image 99
progrmr Avatar answered Oct 14 '22 17:10

progrmr