- Objective-C 基础
- Objective-C - 首页
- Objective-C - 概述
- Objective-C - 环境搭建
- Objective-C - 程序结构
- Objective-C - 基本语法
- Objective-C - 数据类型
- Objective-C - 变量
- Objective-C - 常量
- Objective-C - 运算符
- Objective-C - 循环
- Objective-C - 条件判断
- Objective-C - 函数
- Objective-C - 块 (Blocks)
- Objective-C - 数字
- Objective-C - 数组
- Objective-C - 指针
- Objective-C - 字符串
- Objective-C - 结构体
- Objective-C - 预处理器
- Objective-C - Typedef
- Objective-C - 类型转换
- Objective-C - 日志处理
- Objective-C - 错误处理
- 命令行参数
- 高级 Objective-C
- Objective-C - 类与对象
- Objective-C - 继承
- Objective-C - 多态
- Objective-C - 数据封装
- Objective-C - 分类 (Categories)
- Objective-C - 模拟 (Posing)
- Objective-C - 扩展 (Extensions)
- Objective-C - 协议 (Protocols)
- Objective-C - 动态绑定
- Objective-C - 复合对象
- Obj-C - Foundation 框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C 有用资源
- Objective-C - 快速指南
- Objective-C - 有用资源
- Objective-C - 讨论
Objective-C 数字
在 Objective-C 编程语言中,为了以对象的形式保存像 int、float、bool 这样的基本数据类型,
Objective-C 提供了一系列处理 NSNumber 的方法,重要的方法列在下面的表格中。
| 序号 | 方法及描述 |
|---|---|
| 1 | + (NSNumber *)numberWithBool:(BOOL)value 创建一个包含给定值的 NSNumber 对象,将其视为 BOOL 类型。 |
| 2 | + (NSNumber *)numberWithChar:(char)value 创建一个包含给定值的 NSNumber 对象,将其视为有符号 char 类型。 |
| 3 | + (NSNumber *)numberWithDouble:(double)value 创建一个包含给定值的 NSNumber 对象,将其视为 double 类型。 |
| 4 | + (NSNumber *)numberWithFloat:(float)value 创建一个包含给定值的 NSNumber 对象,将其视为 float 类型。 |
| 5 | + (NSNumber *)numberWithInt:(int)value 创建一个包含给定值的 NSNumber 对象,将其视为有符号 int 类型。 |
| 6 | + (NSNumber *)numberWithInteger:(NSInteger)value 创建一个包含给定值的 NSNumber 对象,将其视为 NSInteger 类型。 |
| 7 | - (BOOL)boolValue 将接收者的值作为 BOOL 类型返回。 |
| 8 | - (char)charValue 将接收者的值作为 char 类型返回。 |
| 9 | - (double)doubleValue 将接收者的值作为 double 类型返回。 |
| 10 | - (float)floatValue 将接收者的值作为 float 类型返回。 |
| 11 | - (NSInteger)integerValue 将接收者的值作为 NSInteger 类型返回。 |
| 12 | - (int)intValue 将接收者的值作为 int 类型返回。 |
| 13 | - (NSString *)stringValue 将接收者的值作为人类可读的字符串返回。 |
这是一个使用 NSNumber 的简单示例,它将两个数字相乘并返回乘积。
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
- (NSNumber *)multiplyA:(NSNumber *)a withB:(NSNumber *)b;
@end
@implementation SampleClass
- (NSNumber *)multiplyA:(NSNumber *)a withB:(NSNumber *)b {
float number1 = [a floatValue];
float number2 = [b floatValue];
float product = number1 * number2;
NSNumber *result = [NSNumber numberWithFloat:product];
return result;
}
@end
int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SampleClass *sampleClass = [[SampleClass alloc]init];
NSNumber *a = [NSNumber numberWithFloat:10.5];
NSNumber *b = [NSNumber numberWithFloat:10.0];
NSNumber *result = [sampleClass multiplyA:a withB:b];
NSString *resultString = [result stringValue];
NSLog(@"The product is %@",resultString);
[pool drain];
return 0;
}
现在,当我们编译并运行程序时,我们将得到以下结果。
2013-09-14 18:53:40.575 demo[16787] The product is 105