Is there a cast keyword in Objective-C like C# (as
):
Foo bar = new Foo();
Foo tmp = bar as Foo;
Is this possible in Objective-C?
Is there a cast keyword in Objective-C like C# (as
):
Foo bar = new Foo();
Foo tmp = bar as Foo;
Is this possible in Objective-C?
There is no direct equivalent of as
in Objective-C. There is regular type casting (C-style).
If you want to check the type of the object, be sure to call isKindOfClass:
.
To write the equivalent of:
Foo bar = new Foo();
Foo tmp = bar as Foo;
You'd write:
Foo *bar = [Foo new];
Foo *tmp = ([bar isKindOfClass:[Foo class]]) ? (Foo *)bar : nil;
You could always write this up as a category like:
@implementation NSObject (TypeSafeCasting)
- (id) asClass:(Class)aClass{
return ([self isKindOfClass:aClass]) ? self : nil;
}
@end
Then you could write it like:
Foo *bar = [Foo new];
Foo *tmp = [bar asClass:[Foo class]];
No, no such keyword exists but you could emulate such behavior with a macro.
#define AS(x,y) ([(x) isKindOfClass:[y class]] ? (y*)(x) : nil)
@interface Foo : NSObject
@end
@implementation Foo
@end
int main(int argc, char *argv[])
{
@autoreleasepool {
Foo *bar = [[Foo alloc] init];
Foo *tmp = AS(bar, Foo);
NSLog(@"bar as Foo: %@", tmp);
bar = [NSArray array];
tmp = AS(bar, Foo);
NSLog(@"bar as Foo: %@", tmp);
}
}
Outputs:
bar as Foo:
<Foo: 0x682f2d0>
bar as Foo: (null)
I would suggest just checking isKindOfClass:
directly rather than using a poorly named macro like AS
. Also if the first paramater of the macro is an expression e.g ([foo anotherFoo]
) it will be evaluated twice. That could lead to performance issues or other issues if anotherFoo
has side effects.
Typecasting (it's just C):
Foo *foo = [[Foo alloc] init];
Bar *bar = (Bar *)foo;
NB: you can shoot yourself in the foot with this, be careful.