3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Objective-Cで `(BOOL)non_nil_obj` がNOになるとき

Last updated at Posted at 2014-01-29

Macで clang -ObjC -framework Foundation non-nil-to-false.m && ./a.out すると実行できます。

#import <Foundation/Foundation.h>

int main() {
    NSObject *value = (id)0x100;
    NSLog(@"value = %d", (BOOL)value);  // value = 0
    NSLog(@"value = %d", (_Bool)value); // value = 1
    return 0;
}

理由はBOOLの定義が以下のようになっているから。

// in objc/objc.h

/// Type to represent a boolean value.
#if !defined(OBJC_HIDE_64) && TARGET_OS_IPHONE && __LP64__
typedef bool BOOL;
#else
typedef signed char BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#endif

まあいろいろ歴史的経緯があるんでしょうけど、たとえ BOOL を使っているとしても、キャストするなら (_Bool) または (bool) とするのがよさそうです。あるいは !!exprexpr ? YES : NO とか。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?