如果我有一个类 id 的对象 myObject,我将如何将其“转换”为 CGPoint(假设我已经执行了自省并且知道 myObject 为 CGPoint)?尽管事实上 CGPoint 不是一个真正的 Obj-C 类。
简单地做(CGPoint)myObject
返回以下错误:
Used type 'CGPoint' (aka 'struct CGPoint') where arithmetic or pointer type is required
我想这样做,以便我可以检查传递给 NSMutableArray 的对象是否是 CGPoint,如果是,则自动将 CGPoint 包装在 NSValue 中;例如:
- (void)addObjectToNewMutableArray:(id)object
{
NSMutableArray *myArray = [[NSMutableArray alloc] init];
id objectToAdd = object;
if ([object isKindOfClass:[CGPoint class]]) // pseudo-code, doesn't work
{
objectToAdd = [NSValue valueWithCGPoint:object];
}
[myArray addObject:objectToAdd];
return myArray;
}
附加代码
以下是我用来执行“内省”的功能:
+ (BOOL)validateObject:(id)object
{
if (object)
{
if ([object isKindOfClass:[NSValue class]])
{
NSValue *value = (NSValue *)object;
if (CGPointEqualToPoint([value CGPointValue], [value CGPointValue]))
{
return YES;
}
else
{
NSLog(@"[TEST] Invalid object: object is not CGPoint");
return NO;
}
}
else
{
NSLog(@"[TEST] Invalid object: class not allowed (%@)", [object class]);
return NO;
}
}
return YES;
}
+ (BOOL)validateArray:(NSArray *)array
{
for (id object in array)
{
if (object)
{
if ([object isKindOfClass:[NSValue class]])
{
NSValue *value = (NSValue *)object;
if (!(CGPointEqualToPoint([value CGPointValue], [value CGPointValue])))
{
NSLog(@"[TEST] Invalid object: object is not CGPoint");
return NO;
}
}
else
{
NSLog(@"[TEST] Invalid object: class not allowed (%@)", [object class]);
return NO;
}
}
}
return YES;
}
+ (NSValue *)convertObject:(CGPoint)object
{
return [NSValue valueWithCGPoint:object];
}