gpt4 book ai didi

iphone - 将 NSNumber 转换为 BOOL Objective-C

转载 作者:可可西里 更新时间:2023-11-01 05:00:46 26 4
gpt4 key购买 nike

我想将整数 01 转换为 BOOLEAN YESNO

我的代码:

    NSNumber *num = 0;
BOOL myBool = [num boolValue];
NSLog(@"bool is: %@",myBool);

输出为 (null)

有什么问题吗?

最佳答案

首先,你的NSNumber的初始化是不正确的。您应该使用定义在 NSNumber:

上的 +numberWith: 类方法之一
+ (NSNumber *)numberWithChar:(char)value;
+ (NSNumber *)numberWithUnsignedChar:(unsigned char)value;
+ (NSNumber *)numberWithShort:(short)value;
+ (NSNumber *)numberWithUnsignedShort:(unsigned short)value;
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithUnsignedInt:(unsigned int)value;
+ (NSNumber *)numberWithLong:(long)value;
+ (NSNumber *)numberWithUnsignedLong:(unsigned long)value;
+ (NSNumber *)numberWithLongLong:(long long)value;
+ (NSNumber *)numberWithUnsignedLongLong:(unsigned long long)value;
+ (NSNumber *)numberWithFloat:(float)value;
+ (NSNumber *)numberWithDouble:(double)value;
+ (NSNumber *)numberWithBool:(BOOL)value;
+ (NSNumber *)numberWithInteger:(NSInteger)value NS_AVAILABLE(10_5, 2_0);
+ (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value NS_AVAILABLE(10_5, 2_0);

BOOL 只是 signed char,因此您不能使用 %@ 格式说明符,但您可以使用任何整数格式说明符,例如 %d%i%c

但是,要输出YESNO,您需要使用字符串:

NSLog(@"bool is: %@", (myBool) ? @"YES" : @"NO");

关于iphone - 将 NSNumber 转换为 BOOL Objective-C ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10341735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com