像数组这样的Foundation集合只能存储对象,不能存储像int这样的基本数据类型。为了解决这个问题,需要使用NSNumber对象数组,而不是int数组。
在iOS程序开发时,还需要在集合中存储其他类型的数据。这些类型源于C语言的一种数据类型,它不是对象。
利用NSValue类可以将C语言的数据类型包装成对象,并可存储在Foundation提供的集合中。
| NSValue包装和展开方法 | |||
| Typedef数据类型 | 描述 | 包装方法 | 展开方法 |
| CGPoint | x和y值组成的点 | valueWithPoint: | pointValue |
| CGSize | 宽和主组成的尺寸 | valueWithSize: | sizeValue |
| CGRect | 矩形包含原点和尺寸 | valueWithRect: | rectValue |
| NSRange | 描述位置和大小的范围 | valueWithRange: | rangeValue |
示例
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
CGPoint myPoint;
NSValue *pointObj;
NSMutableArray *touchPoints = [NSMutableArray array];
myPoint.x = 100;
myPoint.y = 200;
// 包装(wrapping)
pointObj = [NSValue valueWithPoint: myPoint];
[touchPoints addObject: pointObj];
// 取出并展开(unwrapping)
myPoint = [[touchPoints lastObject] pointValue];
}
return 0;
}