zoukankan      html  css  js  c++  java
  • < Objective-C >Foundation-NSNumber

    作用:将基本类型数据封装成对象,便于集合调用


    创建方法:
    +(NSNumber*)numberWithChar:(char)value;
    +(NSNumber*)numberWithInt:(int)value;
    +(NSNumber*)numberWithFloat:(float)value;
    +(NSNumber*)numberWithBool:(BOOL)value;
    获取数据:
    (char)charValue;
    (int)intValue;
    (float)floatValue;
    (BOOL)boolValue;
    (NSString*)stringValue;

    //装箱:基础类型->对象类型
    NSMutableArray *array = [[NSMutableArray alloc]init];
    NSNumber *numberInt = [NSNumber numberWithInt:1];
    [array addObject:numberInt];
            
    //拆箱:对象类型->基础类型
    NSNumber *num = [array objectAtIndex:0];
    NSLog(@"%d",[num intValue]);


    int,NSInteger,NSUinteger,NSNumber的区别
    int:c语言中的整型
    NSInteger:Cocoa中新的整型,不用考虑设备是32位还是64位
    NSUinteger:NSInteger的无符号类型
    int,NSInteger,NSUinteger是基本数据类型,NSNumber是对象类型

    NSValue:NSNumber的父类,将基本数据类型和自定义数据类型(包括指针和结构体等)封装成对象

    系统结构体(以Range为例)

    NSRange range1;
    range1.location = 3;
    range1.length = 5;
    NSValue *rangeValue = [NSValue valueWithRange:range1];
            
    NSRange range2;
    range2 = [rangeValue rangeValue];
    NSLog(@"%ld,%ld",range2.location,range2.length);

    自定义结构体

    //自定义结构体MyPoint
    typedef struct _MyPoint {
        int x;
        int y;
    }MyPoint;
    //MyPoint->NSValue
    MyPoint point1;
    point1.x = 5;
    point1.y = 6;
    NSValue *pointValue = [NSValue valueWithBytes:&point1 objCType:@encode(MyPoint)];
    
    MyPoint point2;
    [pointValue getValue:&point2];
    NSLog(@"%d,%d",point2.x,point2.y);

    关键字@encode():

    Objective-C的数据类型,甚至自定义类型,函数或方法的元类型,都可以使用ascll编码。@encode(aType)返回数据类型的c字符串(char *)的表示

    NSNull:null值的对象类型,用于在集合中存放null值

    //NSNull对象只有一个null值
    [NSNull null];
  • 相关阅读:
    spring boot.定时任务问题记录(TaskScheduler/ScheduledExecutorService异常)
    网站配置https(腾讯云域名操作)
    Java web如何定位工程路径
    centos7安装nginx
    个人博客搭建----基于solo
    velocity学习总结
    第四篇:用IntelliJ IDEA 搭建基于jersey的RESTful api
    Python 包批量升级
    Linux 常用命令更新汇总
    ubuntu 18.04 +firefox + selenium + python
  • 原文地址:https://www.cnblogs.com/aY-Wonder/p/4560519.html
Copyright © 2011-2022 走看看