Search code examples
objective-cios5xcode4.2

Convert NSString to 4 by 4 float Matrix


I was wondering if there is a convenience method or something to change a NSString to an array of floats, for example.

I have a string which reads like this:

{{-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}}

Which I got by the method:

NSStringFromGLKMatrix4()

And i want to do this:

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);

Any help will be appreciated, thanks.


Solution

  • This is kinda ugly, but it should work:

    // 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);
    

    If you're targeting iOS 4.0 or higher, you might also use NSRegularExpression to get the numbers out of the string.