Nic*_*ner 1 oop xcode casting objective-c
在Objective-C中是否有一个像C#(as)这样的强制转换关键字:
Foo bar = new Foo();
Foo tmp = bar as Foo;
Run Code Online (Sandbox Code Playgroud)
在Objective-C中这可能吗?
as在Objective-C中没有直接等效的对象。有常规类型转换(C样式)。
如果要检查对象的类型,请确保调用isKindOfClass:。
要写相当于:
Foo bar = new Foo();
Foo tmp = bar as Foo;
Run Code Online (Sandbox Code Playgroud)
你会写:
Foo *bar = [Foo new];
Foo *tmp = ([bar isKindOfClass:[Foo class]]) ? (Foo *)bar : nil;
Run Code Online (Sandbox Code Playgroud)
您可以始终将其写为以下类别:
@implementation NSObject (TypeSafeCasting)
- (id) asClass:(Class)aClass{
return ([self isKindOfClass:aClass]) ? self : nil;
}
@end
Run Code Online (Sandbox Code Playgroud)
然后,您可以将其编写为:
Foo *bar = [Foo new];
Foo *tmp = [bar asClass:[Foo class]];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1498 次 |
| 最近记录: |