Objective-C之数字对象

发布时间:2020-07-22 12:34:43 作者:Aonaufly
来源:网络 阅读:495

int , float , long都是OC的基本数据类型,但是(!important)它们都不是对象。但是有的时候需要将他们最为一个对象来使用,例如:NSArray要求存储的值必须是对象。那么这里就可以使用NSNumber类。
一 , 为NSNumber赋值:
① : 赋值一个int类型的值,创建和初始化 int2O = [NSNumber numberWithInteger:100]
意义: 为int2O赋值×××100对象
②:获得init2O的的值 init2Get = [init2O integerValue]
注意 : integerValue说明init2O里面存的是int类型的值
例如:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSNumber *init2O;
        NSInteger init2Get;
        init2O = [NSNumber numberWithInteger:100];
        init2Get = [init2O integerValue];
        NSLog(@"%li",(long)init2Get);
    }
    return 0;
}

结果:
Objective-C之数字对象

二,可以使用initWithInteger来直接实例化一个NSNumber

Objective-C之数字对象

其他的类型

赋值方法 实例化 检索方法
numberWithChar initWithChar charValue
numberWithUnsignedChar initWithUnsignedChar unsignedCharValue
numberWithShort initWithShort shortValue
numberWithUnsignedShort initWithUnsignedShort unsignedShortValue
numberWithInteger initWithInteger integerValue
numberWithUnsignedInteger initWithUnsignedInteger unsignedIntegerValue
numberWithInt initWithInt intValue
numberWithUnsignedInt initWithUnsignedInt unsignedIntValue
numberWithLong initWithLong longValue
numberWithUnsignedLong initWithUnsignedLong unsignedLongValue
numberWithLongLong initWithLongLong longlongValue
numberWithUnsignedLongLong initWithUnsignedLongLong unsignedLongLongValue
numberWithFloat initWithFloat floatValue
numberWithDouble initWithDouble doubletValue
numberWithBool initWithBool booltValue

验证2个number是否是相等的

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSNumber *init2O = [[NSNumber alloc] initWithInteger:100];
        NSInteger init2Get;
        init2Get = [init2O integerValue];
        NSLog(@"%li",(long)init2Get);
        //验证是否相等
        NSNumber *float2O = [[NSNumber alloc] initWithFloat:100.00];
        if( [init2O isEqualToNumber:float2O] == YES){
            NSLog(@"Equal!!!");
        }
    }
    return 0;
}

结果:
Objective-C之数字对象
验证小于

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSNumber *init2O = [[NSNumber alloc] initWithInteger:100];
        NSInteger init2Get;
        init2Get = [init2O integerValue];
        NSLog(@"%li",(long)init2Get);
        //验证是否相等
        NSNumber *float2O = [[NSNumber alloc] initWithFloat:100.00];
        if( [init2O compare:float2O] == NSOrderedAscending){
            NSLog(@"Asc!!!");
        }else{
            NSLog(@"No Asc");
        }
    }
    return 0;
}

结果:
Objective-C之数字对象

推荐阅读:
  1. Objective-C之NSArray
  2. Objective-C之字符串对象

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

objective nsnumber 数字对象

上一篇:Windows Server 恢复开机密码

下一篇:一个不错的Cocos 1.6动画编辑器入门教程

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》