记录NSNumber对象封装基本数据类型的用途

开篇

最近遇到几次数据转换问题,并用NSNumber得以解决。才想着总结一下IOS开发中NSNumber这一重要的类

问题记录如下:
1,plist文件中如何读取number、boolean类型数据?
2,json文件中如何读取long类型数据?

以上问题你是否有遇到尼?且看下文

NSNumber定义

  • 1,NSArray、NSDictionary、NSSet 等集合对象只能保存对象。如果要保存 char、short、int、float、double、BOOL 或指向结构的指针等基础数据类型,则可以先将这些基本数据类型封装成 NSNumber 对象,再存入集合对象。
  • 2,NSNumber 类用来包装基本数据类型。
  • 3,NSValue 是 NSNumber 的父类。
  • 4,不能直接用 NSNumber 对象做计算,只能提取值。

值转换

Snip20181221_37.png

Snip20181221_38.png

用途或者案例

1,plist中如何读取number、boolean类型数据?

举例:

创建一个plist文件

Snip20181221_39.png

获取plist文件

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"student" ofType:@"plist"];
    NSMutableDictionary *studentDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

错误的获取方法❌

  • 获取代码
    // /*
    NSString *name = studentDict[@"name"];
    NSUInteger age = studentDict[@"age"];
    NSInteger sex = studentDict[@"sex"];
    BOOL isGoodStudent = studentDict[@"isGoodStudent"];
    BOOL isNortherners = studentDict[@"isNortherners"];
    
    NSLog(@"\n");
    NSLog(@"------------- wrong method log-------------");
    
     NSLog(@"name : %@", name);
     NSLog(@"age : %ld", age);
     NSLog(@"sex : %ld", sex);
     NSLog(@"isGoodStudent : %d", isGoodStudent);
     NSLog(@"isNortherners : %d", isNortherners);
    // */
  • 日志


    Snip20181221_40.png

正确的获取方法✅

  • 获取代码
    NSString *name = studentDict[@"name"];
    NSUInteger age = [(NSNumber *)studentDict[@"age"] unsignedIntegerValue];
    NSInteger sex = [(NSNumber *)studentDict[@"sex"] integerValue];
    BOOL isGoodStudent = [(NSNumber *)studentDict[@"isGoodStudent"] boolValue];
    BOOL isNortherners = [(NSNumber *)studentDict[@"isNortherners"] boolValue];
    
    
    NSLog(@"\n");
    NSLog(@"------------- right method log-------------");

    NSLog(@"name : %@", name);
    NSLog(@"age : %ld", age);
    NSLog(@"sex : %ld", sex);
    NSLog(@"isGoodStudent : %d", isGoodStudent);
    NSLog(@"isNortherners : %d", isNortherners);
  • 日志


    Snip20181221_41.png

2,json文件中如何读取long类型数据?

举例:

  • 创建一个json文件,添加一个键值
{
    "review": 1
}
  • 读取该文件中review键对应的值
    NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"init" ofType:@"json"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:filePath2];
    NSMutableDictionary *jspnDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSLog(@"\n");
    NSLog(@"jspnDict : %@", jspnDict);

    long review = [(NSNumber *)jspnDict[@"review"] longValue];
    NSLog(@"\n");
    NSLog(@"------------- getJSONFileData log-------------");
    
    NSLog(@"review : %ld", review);
  • log
jspnDict : {
    review = 2;
}

------------- getJSONFileData log-------------
review : 2

参考:
1,https://www.jianshu.com/p/0f6a4fe4d222
2,https://www.jianshu.com/p/6fa0926dd478
3,官方文档:https://developer.apple.com/documentation/foundation/nsnumber?language=objc

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。