What is the best practice for storing CoreGraphics struct based values such as CGRect, CGPoint, etc into proper objects for the purpose of storing in collection classes?
You can either use NSValue:
NSMutableArray *values = [NSMutableArray array];
CGRect rect = CGRectMake(0, 0, 100, 100);
NSValue *value = [NSValue valueWithCGRect:rect];
[values addObject:value];
CGRect rectValue = [values[0] CGRectValue];
or NSString:
NSMutableArray *values = [NSMutableArray array];
CGRect rect = CGRectMake(0, 0, 100, 100);
NSString *string = NSStringFromCGRect(rect);
[values addObject:string];
CGRect rectValue = CGRectFromString(string);
Just wondering if there was something I was missing and there was an advantage to one over the other.
The first way is more “canonical” because it has smaller footprint in memory, and does not require much CPU to do the conversion. There is also no possibility of the precision loss due to conversion to decimal and back: the floats inside the
structs are stored in their native format.To be fair, the differences between the two approaches are negligible, unless you need to deal with tens of thousands of objects.