回到我每天的愚蠢问题。今天我试图把一个结构放在一个 NSArray 中。好吧,这很简单,将它包装在一个 NSData 中。如果你认识我,你就会知道你即将看到代码。在此示例中,我将 Wavefront OBJ 中的顶点线加载到结构中并将其粘贴到数组中。
NSArray *verticeLineParts = [currentLine componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Coordinate c = CoordinateMake([[verticeLineParts objectAtIndex:1] floatValue],
[[verticeLineParts objectAtIndex:2] floatValue],
[[verticeLineParts objectAtIndex:3] floatValue]);
[vertices addObject:[[NSData alloc] initWithBytes:&c length:sizeof(c)]];
这似乎工作正常。输出中的前几个对象:
2010-10-18 14:18:08.237 ObjLoader[3778:207] (
<5d1613bd 13f3da3f 8ac745bd>,
<f04c28bd 13f3da3f d88048bd>,
<649427bd d61ddb3f d88048bd>,
<477625bd d845db3f d88048bd>,
<4c1722bd 1668db3f d88048bd>,
在将它们从阵列中拉出后将它们打印出来时,并没有那么多。违规代码:
for (int i = 0; i < [vertices count]; i++) {
Coordinate c;
fillCoordinateFromData(c, [vertices objectAtIndex:i]);
NSLog(@"%@", CoordinateToNSString(c));
}
[snip]
void fillCoordinateFromData(Coordinate c, NSData *d) {
void *bytes = malloc(12);
[d getBytes:bytes];
memcpy((void *)&c, &bytes, 12);
free(bytes);
}
当然,有问题的输出:
2010-10-18 14:22:00.692 ObjLoader[3825:207] 9.885923, -6.837428, 0.000000
2010-10-18 14:22:00.693 ObjLoader[3825:207] 9.885923, -6.837428, 0.000000
2010-10-18 14:22:00.694 ObjLoader[3825:207] 9.885923, -6.837428, 0.000000
2010-10-18 14:22:00.695 ObjLoader[3825:207] 9.885923, -6.837428, 0.000000
2010-10-18 14:22:00.695 ObjLoader[3825:207] 9.885923, -6.837428, 0.000000
我认为这是由不是 C 巫师的人尝试的 C 巫术造成的,有点像《巫师的学徒》。我认为这对于 99 级的巫师来说应该是显而易见的,或者如果有人可以提出更现代的方法来做到这一点,请告诉我。
谢谢,威尔