zakdances
zakdances

Reputation: 23685

Collection element of type 'CGSize' is not an Objective-C object

I'm trying a give a NSDictionary key value a CGSize, and XCode is giving me this error. My code:

       NSArray *rows = @[
        @{@"size" : (CGSize){self.view.bounds.size.width, 100}
          }
        ];

Why am I getting an error here? If its impossible to store a CGSize in a dict, then what's an alternative approach?

EDIT: now getting "Used type 'CGSize' (aka 'struct CGSize') where arithmetic, pointer, or vector type is required" error with this code:

NSDictionary *row = rows[@0];
CGSize rowSize = [row[@"size"] CGSizeValue] ? : (CGSize){self.view.bounds.size.width, 80};

Upvotes: 8

Views: 7069

Answers (2)

prewett
prewett

Reputation: 1647

Kevin's answer only works on iOS; for Mac OS X (Cocoa) do:

[NSValue valueWithSize:NSMakeSize(self.view.bounds.size.width, 100)];

Upvotes: 0

Lily Ballard
Lily Ballard

Reputation: 185681

CGSize is not an object. It's a C struct. If you need to store this in an obj-c collection the standard way is by wrapping it in NSValue, like so:

NSArray *rows = @[
 @{@"size" : [NSValue valueWithCGSize:(CGSize){self.view.bounds.size.width, 100}]
  }
];

Then later when you need to get the CGSize back, you just call the -CGSizeValue method, e.g.

CGSize size = [rows[0][@"size"] CGSizeValue];

Upvotes: 24

Related Questions