Thursday, February 2, 2012

iOS - Store CGPoint in NSArray or NSDictionary

Ever tried to add a CGPoint variable to an NSArray or NSDictionary?
Did you received the following error message ?
error: sending 'CGPoint' (aka 'struct CGPoint') to parameter of incompatible type 'id'

If so than following code snippet should be of good help to you:

NSArray *myPoints = [NSArray arrayWithObjects:
                     [NSValue valueWithCGPoint:CGPointMake(10.f,20.f)],

To restore your CGPoint value again just use following :

NSValue *myValue = [myPoints objectAtIndex:0];
CGPoint myPoint = [myValue CGPointValue];
Or in short :

CGPoint myPoint = [[myPoints objectAtIndex:0] CGPointValue] 

In case you never came across NSValue, just have a read through on the NSValue Class Reference.
As you can see, NSValue can come in quite handy.