一 问题描述
类对象的属性id类型是NSNumber ,设置UI 的 tag(NSInteger类型)时候,数据失真。
id属性是1,tag 取出来为19。
1.1 UI tag 属性
// @property(nonatomic) NSInteger tag;
1.2 错误代码如下
//tagNumber 是 NSNumber 类型 [button setTag:tagNumber];
1.3 修改代码如下
//通过integerValue方法 中转 [button setTag:[tagNumber integerValue]];
1.4 问题模拟
//1.声明 NSInteger 对象 NSInteger integer = 0; //2.声明 NSNumber 对象 NSNumber *number = [NSNumber numberWithInt:3]; integer = number; NSLog(@"integer:%d",integer); NSLog(@"integer:%ld",integer); ===设置的是 3 输出的却是非 3 integer:50 integer:-5764607523034234830
注意:NSNumber 对象不能直接赋值给NSInteger 变量,会导致数据失真,需要通过方法中转
二 两者区别
NSInteger 是基本类型,是int类型的typedef,被typedef成long(64位) 和的int(32位)
NSNumber 是类,包含多种数据类型的对象,提供多个方法来初始化对象,和其他操作方法
NSNumber.h头文件
- (NSNumber *)initWithChar:(char)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithUnsignedChar:(unsigned char)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithShort:(short)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithUnsignedShort:(unsigned short)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithInt:(int)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithUnsignedInt:(unsigned int)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithLong:(long)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithUnsignedLong:(unsigned long)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithLongLong:(long long)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithUnsignedLongLong:(unsigned long long)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithFloat:(float)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithDouble:(double)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithBool:(BOOL)value NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithInteger:(NSInteger)value NS_AVAILABLE(10_5, 2_0) NS_DESIGNATED_INITIALIZER; - (NSNumber *)initWithUnsignedInteger:(NSUInteger)value NS_AVAILABLE(10_5, 2_0) NS_DESIGNATED_INITIALIZER;
参考stackoverflow:NSNumber NSInteger 两者其别
三 互转方法
//把int 转换成NSNumber NSNumber *aNumber = [NSNumber numberWithInteger:21]; //把NSNumber 对象转换成 NSInteger NSInteger anInteger = [aNumber integerValue];
时间: 2024-10-13 04:33:56