shah1988
shah1988

Reputation: 2684

Get CGSize from NSString

In my web service response I get the value of one of my JSON key as follows:

{
dimensions = "1200, 800";
displayName = "something";
displayNumber = 1;
}

I need to convert the dimensions string to a CGSize variable and I use the following code. I got the JSON dictionary to an NSDictionary name wardsDictionary and did the following:

NSString *dimensionsString = (NSString *)[wardsDictionary objectForKey:@"dimensions"];
CGSize wardDimensions = CGSizeFromString(dimensionsSizeString);
NSLog(@"the dimensions string: %@",dimensionsString);
NSLog(@"the width: %@ and height:%@", wardDimensions.width, wardDimensions.height);

And the result was:

the dimensions string: "1200, 800"
the width: 0.0000 and height:0.0000

Now what I am trying to do here is to get components separated by "," and get the CGSize variable from it. But is there a good way to actually achieve this directly?

Upvotes: 2

Views: 1602

Answers (2)

Good Doug
Good Doug

Reputation: 2072

The issue is that CGSizeFromString requires the string to be in the format: "{1200, 800}" you can either append the brackets to either side, or do the componentsSeparatedByString:@"," and then get the intValue for the components:

NSArray *parts = [dimensionsString componentsSeparatedByString:@","];
float width = [parts.firstObject floatValue];
float height = [parts.lastObject floatValue];
CGSize size = CGSizeMake(width, height);

Upvotes: 7

DilumN
DilumN

Reputation: 2895

If you can edit your web service, separate dimension key to height & width keys. Then you can easily use those keys to create CGSize.

If it's not possible the only way is separate by "," & assign the values to CGSizeMake.

Upvotes: 0

Related Questions