我想知道是否有一种方便的方法或者某种东西可以将NSString更改为一个浮点数组,例如。
我有一个字符串,如下所示:
{{-0.528196, -0.567599, -0.631538, 0}, {0.0786662, -0.773265, 0.629184, 0}, {-0.845471, 0.282651, 0.453086, 0}, {0, 0, 0, 1}}
我通过该方法得到了:
NSStringFromGLKMatrix4()
我想这样做:
float test[4][4] = {{-0.528196, -0.567599, -0.631538, 0}, {0.0786662, -0.773265, 0.629184, 0}, {-0.845471, 0.282651, 0.453086, 0}, {0, 0, 0, 1}};
return GLKMatrix4MakeWithArray(*test);
任何帮助将不胜感激,谢谢。
答案 0 :(得分:1)
这有点难看,但应该有效:
// your string data
NSString* s = @"{{-0.528196, -0.567599, -0.631538, 0}, {0.0786662, -0.773265, 0.629184, 0}, {-0.845471, 0.282651, 0.453086, 0}, {0, 0, 0, 1}}";
// remove uneccessary characters from string..
s = [s stringByReplacingOccurrencesOfString:@"{" withString:@""];
s = [s stringByReplacingOccurrencesOfString:@"}" withString:@""];
s = [s stringByReplacingOccurrencesOfString:@" " withString:@""];
// build an NSArray with string components and convert them to an array of floats
NSArray* array = [s componentsSeparatedByString:@","];
float data[16];
for(int i = 0; i < 16; ++i){
data[i] = [[array objectAtIndex:i] floatValue];
}
GLKMatrix4 matrix = GLKMatrix4MakeWithArray(data);
如果您的目标是iOS 4.0或更高版本,您也可以使用NSRegularExpression
从字符串中获取数字。
答案 1 :(得分:1)
显然,好的安西斯...... sscanf ......很久以来就被遗忘了。
sscanf(...,"{{%f,%f,%f,%f}, ...",...);
您可以在hexString帖子中查看我的sscanf代码作为附加示例。
答案 2 :(得分:0)
使用componentsSeparatedByString:
NSString
方法检索数组中的值,然后使用
GLKMatrix4MakeWithArray
方法。
答案 3 :(得分:0)
使用NSValue,这是Apple提供的更好的替代方案,用于在C类型结构和Objective-C对象之间进行转换。
<强>编码
GLKMatrix4 encMatrix = /* your matrix */;
NSValue *encMatrixValue = [NSValue value:&encMatrix withObjCType:@encode(GLKMatrix4)];
<强>解码强>
GLKMatrix4 decMatrix;
[encMatrixValue getValue:&decMatrix];
这比将GLKMatrix转换为NSString并返回GLKMatrix更加清洁和稳定。