Ken*_*rty 1 casting class objective-c cgpoint
如果我有一个类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;
}
Run Code Online (Sandbox Code Playgroud)
附加代码
以下是我用来执行"内省"的功能:
+ (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];
}
Run Code Online (Sandbox Code Playgroud)
A CGPoint不是Objective-C对象.你不能将一个传递给你的addObjectToNewMutableArray:方法.编译器不会让你.
您需要包装CGPointin NSValue并将该包装器传递给您的addObjectToNewMutableArray:方法.
如果您有,NSValue并且您想测试它是否包含a CGPoint,您可以这样问:
if (strcmp([value objCType], @encode(CGPoint)) == 0) {
CGPoint point = [value CGPointValue];
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3804 次 |
| 最近记录: |