當你想使用Cocoa的集合來存儲非對象型數據時,NSValue和NSNumber是非常有用的。NSNumber是NSValue的子類,所以 NSValue更靈活一些。
我們先看看NSValue能做什么:
一個NSValue對 象是用來存儲一個C或者Objective-C數據的簡單容器。它可以保存任意類型的數據,比如int,float,char,當然也可以是指pointers, structures, and object ids。NSValue類的目標就是允許以上數據類型的數據結構能夠被添加到集合里,例如那些需要其元素是對象的數據結構,如NSArray或者NSSet 的實例。需要注意的是NSValue對象一直是不可枚舉的。
所以下面的代碼是可行的:
// assume ImaginaryNumber defined:
typedef struct {
float real;
float imaginary;
} ImaginaryNumber;
ImaginaryNumber miNumber;
miNumber.real = 1.1;
miNumber.imaginary = 1.41;
NSValue *miValue = [NSValue value:miNumber
withObjCType:@encode(ImaginaryNumber)]; // encode using the type name
ImaginaryNumber miNumber2;
[miValue getValue:&miNumber2];
|
是不是影像很深刻呢?然而不管怎樣,蘋果的文檔里有一 行看起來有點含混的解釋:
時刻記住你的struct類型必須是定長的。你不可以存儲C字符串,不定長數組和結構和其他的一些不定長 的數據類型到NSValue中去。你應該使用NSString或者NSData來存儲此類不定長數據。當然你可以把一個指向變長對象的指針存儲在 NSValue對象中。
這是什么意思呢?如果你的數據不是定長的會發生什么?它能被正確的存儲下來嗎?
typedef struct {
int dataSize;
char *data;
int year;
} myStructType1;
|
當data指向一個字符數組時,它能被正確的編碼嗎?
回 答是很簡單的,它是變長的,所以它指向的數據不會被編碼。
只有這個指針地址被編碼了。所以,如果你有一個服務線程編碼了一個 myStructTyle1的數據發布出去,并釋放了這快內存,那么客戶線程拿到這個數據解碼并試圖獲取data的原始數據時,那就只能得到data的指 針地址,而不是數據內容。所以不要期望它能存儲你的data。你應該使用NSData或者NSArchiver來代替NSValue以達到期望目標。
我 們再看這個例子:
typedef struct {
int age;
int month;
int day;
} innerType;
typedef struct {
int dataSize;
innerType *innerData;
} myStructType2;
|
恩,innerTyle是一個定長的類型變量,那么它會被正確 編碼嗎?
不會,蘋果的文檔并沒有說明此類情況。它依然只編碼指針而不是內容。
所以在這種情況下,依然得使用NSData。
總結, 使用NSValue只能是對那些沒有變量是指針的struct。
Then how the NSValue stores? It is kind of shallow copy. Please read this.
Here the address of myCString is passed (&myCString), so the address of the first character of the string is stored in theValue. Note that the NSValue object doesn’t copy the contents of the string, but the pointer itself. If you create an NSValue object with an allocated data item, don’t deallocate its memory while the NSValue object exists.
=============================== 我是引用分割線=================
不管是NSValue還是NSData,都是可以對非對象進行編碼存儲的。但在我的工 程里,線程之間通信的數據是需要進行序列化的,我使用了NSKeyedArchiver來序列化。
在使用過程中發現NSValue存儲的數據不可 被序列化,而NSData可以。我的struct是定長的。
所以最好包裝時都使用NSData吧,如果時rect, point之類的倒是可以用NSvalue,它已經提供好接口供你使用了。
用NSValue試了半天.保存CGSize不行.
后來改用NSData好了..
復制代碼
- UIImage *currentImg = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",i]];
- CGSize imageSize = currentImg.size;
- NSData *pointObjectIn = [NSData dataWithBytes:&imageSize length:sizeof(CGSize)];
- [persistentArray addObject:pointObjectIn];
|
復制代碼
- NSData* getImgeData = [arrayImageCGSize objectAtIndex:i] ;
- CGSize imageSize = *(CGSize*)[getImgeData bytes];
|
From: http://www.cocoachina.com/bbs/read.php?tid-13738.html
@import url(http://www.shnenglu.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);