[英]Encode 2D Array in Objective-c
I have a custom object with two 2D arrays as follows: 我有一个带有两个2D数组的自定义对象,如下所示:
float a[5][5];
float b[5][10];
And I want to encode this object: 我想编码这个对象:
- (void)encodeWithCoder:(NSCoder *)coder
{
// Encode a
// Encode b
}
How can I encode and decode these 2D arrays? 如何编码和解码这些2D阵列? I couldn't find an appropriate method to do this operation.
我找不到合适的方法来执行此操作。 Thanks in Advance,
提前致谢,
You can create a struct with those: 您可以使用以下内容创建结构:
typedef struct myStruct {
float a[5][5];
float b[5][10];
}MyStruct;
Then use NSValue to encode them as objects. 然后使用NSValue将它们编码为对象。
MyStruct i;
memset(&i, 0, sizeof(i));
//Set values on struct
NSValue *v = [NSValue valueWithBytes:&i objCType:@encode(MyStruct)];
Now, you can treat your struct as an object and use then with NSArrays and so on. 现在,您可以将结构视为对象,然后与NSArrays等配合使用。
To read the values you can use: 要读取值,可以使用:
MyStruct i;
[v getValue:&i];
I did it like this to work with streams and legacy servers and it worked smoothly. 我这样做是为了与流和旧式服务器一起使用,并且运行顺利。
Hope it helps. 希望能帮助到你。
将它们粘贴到Objective-C容器中以进行编码/解码过程。
There is no pre-built method for that - you would need to write it yourself. 没有预构建的方法-您需要自己编写。 The simplest way would be to write two
int
s first for the number of rows and the number of columns, and then write all R*C
elements one by one. 最简单的方法是先为行数和列数写两个
int
,然后一个一个地写所有R*C
元素。
Decoding is equally simple - read the two ints for R
and C
, and then run two nested loops reading the float
s. 解码同样简单-读取
R
和C
的两个整数,然后运行两个嵌套循环以读取float
。
Define two helper functions for that to avoid copy-pasting the same code twice. 为此定义两个辅助函数,以避免两次复制相同的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.