NSNumber基本用法

NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char, short int, int, long int, long long int, float, or double or as a BOOL. (Note that number objects do not necessarily preserve the type they are created with.) It also defines a compare: method to determine the ordering of two NSNumber objects.


#import 

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        /* NSArray用于NSObject对象的集合,为了能使用基本类型,需要通过NSNumber转换 */
        NSNumber *intNum1 = [[NSNumber alloc] initWithInt: 1];
        NSNumber *intNum2 = [[NSNumber alloc] initWithInt: 2];
        NSNumber *charNum1 = [[NSNumber alloc] initWithChar: 'A'];
        NSNumber *floatNum1 = [[NSNumber alloc] initWithFloat: 1.2];
        NSNumber *doubleNum1 = [[NSNumber alloc] initWithDouble: 3.4];
        NSArray *arr = [[NSArray alloc] initWithObjects: intNum1, intNum2, charNum1,
                        floatNum1, doubleNum1, nil];
        NSLog(@"arr is:%@", arr);
        
        /* 比较 */
        BOOL ret = [intNum1 isEqualToNumber: intNum2];
        NSLog(@"ret:%d", ret);
        NSComparisonResult result = [intNum1 compare:intNum2];
        if (result == NSOrderedAscending)
        {
            NSLog(@"<");
        }
        else if (result == NSOrderedSame)
        {
            NSLog(@"==");
        }
        if (result == NSOrderedDescending)
        {
            NSLog(@">");
        }
        
        /* 从NSNumber中获取基本类型值 */
        int a = [intNum1 intValue];
        float b = [floatNum1 floatValue];
        char c = [charNum1 charValue];
        double d = [doubleNum1 doubleValue];
        NSLog(@"%d,%f,%c,%lf", a,b,c,d);
    }
    return 0;
}
输出结果:

2015-11-24 22:29:37.356 TestNSNumber[485:12892] arr is:(
    1,
    2,
    65,
    "1.2",
    "3.4"
)
2015-11-24 22:29:37.356 TestNSNumber[485:12892] ret:0
2015-11-24 22:29:37.356 TestNSNumber[485:12892] <
2015-11-24 22:29:37.357 TestNSNumber[485:12892] 1,1.200000,A,3.400000


你可能感兴趣的:(iOS)