0%

OC BOOL类型

下面的代码:

1
2
3
signed char rs = 240;
BOOL rs1 = 240;
NSLog(@"%d %d", rs, rs1);

在32位机,如iPhone5c上输出为:-16 -16.
在64位机,如iPhone6s上输出为:-16 1.

在SDK usr/include/objc/objc.h里的定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/// Type to represent a boolean value.

#if defined(__OBJC_BOOL_IS_BOOL)
// Honor __OBJC_BOOL_IS_BOOL when available.
# if __OBJC_BOOL_IS_BOOL
# define OBJC_BOOL_IS_BOOL 1
# else
# define OBJC_BOOL_IS_BOOL 0
# endif
#else
// __OBJC_BOOL_IS_BOOL not set.
# if TARGET_OS_OSX || TARGET_OS_MACCATALYST || ((TARGET_OS_IOS || 0) && !__LP64__ && !__ARM_ARCH_7K)
# define OBJC_BOOL_IS_BOOL 0
# else
# define OBJC_BOOL_IS_BOOL 1
# endif
#endif

#if OBJC_BOOL_IS_BOOL
typedef bool BOOL;
#else
# define OBJC_BOOL_IS_CHAR 1
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#endif

#define OBJC_BOOL_DEFINED

#if __has_feature(objc_bool)
#define YES __objc_yes
#define NO __objc_no
#else
#define YES ((BOOL)1)
#define NO ((BOOL)0)
#endif

大概意思就是:
默认情况下,在32位iPhone上,BOOL就是signed char类型(1个字节。-128 ~ 127)
在64位iPhone上,BOOL就是bool类型.而bool类型的值有两种true(1)和false(0).任何不为0的数强转为bool类型,均转为true(即非0都为真).

另外:

- (id)performSelector:(SEL)aSelector withObject:(id)object;参数问题.
结论:performSelector的object参数只能为对象类型,其selector参数对应方法的参数也必须为对象类型,如果为基本数据类型则值不可预知,这个时候只能使用NSInvocation.

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, assign) BOOL val;

@property (nonatomic, assign) int num;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

self.val= YES;
}

- (void)changeMyVal:(BOOL)param {
NSLog(@"%d", param);
self.val = param;
NSLog(@"%d", self.val);
}

- (void)changeNumber:(int)param {
NSLog(@"%d", param);
self.num = param;
NSLog(@"%d", self.num);
}

- (void)changeNumberObj:(NSNumber *)param {
NSLog(@"%d", param.intValue);
self.num = param.intValue;
NSLog(@"%d", self.num);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];

//performSelector的object参数只能为对象类型,其selector参数对应方法的参数也必须为对象类型,如果为基本数据类型则值不可预知.
[self performSelector:@selector(changeMyVal:) withObject:@(0) afterDelay:2]; //self.val的值每次运行随机0或1
// [self performSelector:@selector(changeMyVal:) withObject:@(1) afterDelay:2]; //self.val的值每次运行随机0或1.大多数情况下是0
// [self performSelector:@selector(changeMyVal:) withObject:@(234) afterDelay:2]; //self.val的值每次运行随机0或1.

// [self performSelector:@selector(changeNumber:) withObject:@(25) afterDelay:2]; //self.num = -1985119076;(每次运行都不一样的)

// [self performSelector:@selector(changeNumberObj:) withObject:@(25) afterDelay:2]; //self.num = 25;
}


@end
觉得文章有帮助可以打赏一下哦!