2013年1月11日 星期五

NSValue的使用

當你想使用Cocoa的集合來存儲非對象型數據時,NSValue和NSNumber是非常有用的。 NSNumber是NSValue的子類,所以NSValue更靈活一些。我們先看看NSValue能做什麼: 
一個NSValue對像是用來存儲一個C或者Objective-C數據的簡單容器。它可以保存任意類型的數據,比如int,float,char,當然也可以是指pointers, structures, and object ids。 NSValue類的目標就是允許以上數據類型的數據結構能夠被添加到集合裡,例如那些需要其元素是對象的數據結構,如NSArray或者NSSet 的實例。

另外注意,如果要用struct的指向變數,要使用NSData,有機會再整理相關資料。

下面使用NSMutableArray來作例子 

將CGPoint放入NSMutable Array
NSMutableArray *linePointsArray = [[NSMutableArray alloc] init];
CGPoint lastPoint = CGPointMake(5.5, 6.6)]

[linePointsArray addObject:[NSValue valueWithCGPoint:lastPoint]]; // add a CGPoint


從Array中取出 CGPoint
 NSValue *val = [linePointsArray objectAtIndex:0];
  CGPoint p = [val CGPointValue];



另外int 變數也可以如此用

myArray = [NSMutableArray array];
[myArray addObject:[NSNumber numberWithInteger:1234]];

//..

 int theNumber = [[myArray objectAtIndex:0] integerValue];

沒有留言: