Objective-C 基本类型转换问题
考虑下面的代码:
if([obj isKindOfClass:[NSString class]]) {
NSString *s = [(NSString *)obj stringByAppendingString:@"xyzzy"];
}
我在这里有点困惑。 if
语句检查 obj
是否属于 NSString
类。如果是,它会将对象和附加字符串分配给 NSString *s
,我理解正确吗?如果是这样,为什么还要将其转换为 (NSString *)
? if
语句是否已经检查过这一点,并且这是否使得类型转换变得不必要?
难道直接说:
NSString *s = obj stringByAppendingString:@"xyzzy"];
提前致谢。
Consider the following code:
if([obj isKindOfClass:[NSString class]]) {
NSString *s = [(NSString *)obj stringByAppendingString:@"xyzzy"];
}
I'm a bit confused here. The if
statement checks whether or not obj
is of the NSString
class. If it is, it assigns the object and an appended string to NSString *s
, do I understand this correctly? If so, why would you still cast it to (NSString *)
?
Doesn't the if
statement already check for that and doesn't that make the typecasting unnecessary?
Wouldn't it be perfectly fine to just say:
NSString *s = obj stringByAppendingString:@"xyzzy"];
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这完全取决于 obj 的定义方式。如果它是 id obj 则不需要转换,但如果它被定义为 NSObject *obj 则需要转换来抑制编译器警告
stringByAppendingString:
未在NSObject
上定义。不需要强制转换来使代码在运行时工作,它只是告诉编译器“正确”的类型,以便它可以判断该方法是否应该存在于对象上。id
不需要强制转换的原因是id
表示“任何类型的对象”,而NSObject *
表示“NSObject 类型的对象”。It all depends on how
obj
is defined. If it isid obj
then no casting is needed, but if it was defined asNSObject *obj
the cast is necessary to suppress the compiler warning thatstringByAppendingString:
is not defined onNSObject
. The cast is not needed to make the code work at runtime, it only tells the compiler the "correct" type so it can tell whether the method should exist on the object.The reason why the cast isn't needed for
id
is becauseid
means "an object of any type", whileNSObject *
means "an object of type NSObject".