zoukankan      html  css  js  c++  java
  • int, NSInteger, NSUInteger, NSNumber的区别

     

    新手在接触iOS或者Mac开发的时候,看到int和NSInteger,一般不清楚应该用哪个比较合适。我们先来查看下NSInteger的定义
    #if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
    typedef long NSInteger;
    typedef unsigned long NSUInteger;
    #else
    typedef int NSInteger;
    typedef unsigned int NSUInteger;
    #endif

    可以看到苹果的NSInteger,其实可以根据iOS或者Mac设备的不同(32或64)自动选用最大的值,int long.因此更推荐使用NSInteger而不是int,更符合规范。
    至于NSUinteger,则是指无符号的,一般用于索引值,比如在Tableview里,NSUInteger row= [indexPath row];

    有人就想,既然可以用NSInteger了,为何还出现NSNumber?
    NSNumber是定义的一个类,用于封装int,float等基本类型。比如在NSMutableArray的
    - (void)addObject:(id)anObject
    需要传入id类型,传入一个带指针类型的,而NSInteger上述定义,可知不属于此列。
    示例:
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    NSNumber *number = [NSNumber numberWithInt:2]
    [mutable addObject:number];

  • 相关阅读:
    iOS_核心动画(二)
    iOS_核心动画CALayer(一)
    iOS_KVC与KVO
    iOS_Quartz 2D绘图
    iOS_触摸事件与手势识别
    iOS_多线程(二)
    iOS_多线程(一)
    iOS_UIAlertController
    CTF-Pwn-[BJDCTF 2nd]diff
    数据结构--队列(Java实现)
  • 原文地址:https://www.cnblogs.com/sparks/p/3828526.html
Copyright © 2011-2022 走看看