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之数字对象]()
本文转自Aonaufly51CTO博客,原文链接:http://blog.51cto.com/aonaufly/2054108 ,如需转载请自行联系原作者