2

当该属性是 CGRect 时,如何设置实例的属性。我想做这个:

CGRect rect = CGRectFromString(value);
[localClassObjectInstance setValue:rect forKey:key];

但编译器不喜欢 setValue;它说我将 CGRect 发送到不兼容类型“id”的参数。

谢谢

4

2 回答 2

9

您必须将 CGRect 转换为 NSValue (反之亦然):


NSValue *myValue = [NSValue valueWithCGRect:rect];

NSValue 是一个对象(所以它的类型是“id”)。

然后你可以得到 CGRect 回来:


CGRect myRect = [myValue CGRectValue];
于 2012-06-07T13:02:22.070 回答
2

NSValue and NSNumber are to handle cases when the value is not an obj-c object:

NSRect rect = ...;
[object setValue:[NSValue valueWithRect:rect] forKey:key];

NSValue* val = [object valueForKey:key];
NSRect extractedRect = [val rectValue];

To store GCRect with Mac OS X SDK, you have to convert it to NSRect first using NSRectFromCGRect and NSRectToCGRect functions. On iOS, there are valueWithCGRect/CGRectValue methods instead (see @viggio24 answer).

于 2012-06-07T13:01:57.440 回答