How to handle float values in a plist

Posted by Banjer on Stack Overflow See other posts from Stack Overflow or by Banjer
Published on 2010-04-14T01:58:52Z Indexed on 2010/04/14 2:03 UTC
Read the original article Hit count: 393

Filed under:
|
|

I'm reading in a plist from a web server, generated with some php. When I read that into an NSArray in my iphone app, and then spit the NSArray out with NSLog to check it out, I see that the float values are treated as strings. I would like the "distance" values to be treated as numeric and not strings. This plist is displayed in a table view where it can be sorted by distance, but the problem is is distance is sorted as a string, so I get some funny sorting results.

Can I convert the distance values to float from string in the NSArray? Or maybe theres a simpler solution like tweaking the plist definition, or maybe something in the NSMutableURLRequest code?

My plist looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
  <dict>
    <key>name</key>
    <string>Pizza Joint</string>
    <key>distance</key>
    <string>2.1</string>
  </dict>
  <dict>
    <key>name</key>
    <string>Burger Kang</string>
    <key>distance</key>
    <string>5</string>
  </dict>
</array>
</plist>

After reading it into an NSArray, it looks like this per NSLog:

    result: (
      {
        distance = "2.1";
        name = "Pizza Joint";
      },
        {
        distance = 5;
        name = "Burger Kang";
      }
    )

Here is the Objective-C code that retrieves the plist:

// Set up url request
// postData and postLength are left out, but I can post in this question if needed.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://mysite.com/get_plist.php"]];  
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];     


NSError *error;
NSURLResponse *response;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *string = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
// libraryContent is an NSArray
self.libraryContent = [string propertyList];
NSLog(@"result: %@", self.libraryContent);

© Stack Overflow or respective owner

Related posts about plist

Related posts about objective-c