Objective-C 基本类型转换问题

发布于 2024-11-16 06:11:38 字数 489 浏览 3 评论 0原文

考虑下面的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

身边 2024-11-23 06:11:38

这完全取决于 obj 的定义方式。如果它是 id obj 则不需要转换,但如果它被定义为 NSObject *obj 则需要转换来抑制编译器警告stringByAppendingString: 未在 NSObject 上定义。不需要强制转换来使代码在运行时工作,它只是告诉编译器“正确”的类型,以便它可以判断该方法是否应该存在于对象上。

id 不需要强制转换的原因是 id 表示“任何类型的对象”,而 NSObject * 表示“NSObject 类型的对象”。

It all depends on how obj is defined. If it is id obj then no casting is needed, but if it was defined as NSObject *obj the cast is necessary to suppress the compiler warning that stringByAppendingString: is not defined on NSObject. 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 because id means "an object of any type", while NSObject * means "an object of type NSObject".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文