gpt4 book ai didi

ios - Objective-C:NSMutableArray 的未转换元素返回意外类型

转载 作者:行者123 更新时间:2023-12-01 18:45:51 25 4
gpt4 key购买 nike

如果无法理解以下内容。考虑以下代码:

UIImage *image = [[UIImage alloc] initWithContentsOfFile:@"car.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:imageView];

UIImage *image2 = [imageView image];
UIImage *image3 = [[array objectAtIndex:0] image];
UIImage *image4 = [(UIImageView *) [array objectAtIndex:0] image];

image2 和 image4 的说明按预期工作。另一方面,带有 image3 的行显示了一个问题,

Incompatible pointer types initializing 'UIImage *' with an expression of type 'CIImage *'



我知道不对从 NSMutableArray 检索到的对象进行类型转换可能会导致问题。但是,我很难理解为什么编译器会认为这个表达式是 CIImage 类型。 .

如果这个问题被问得更笼统,我很抱歉,我找不到它......

最佳答案

让我们把它分开:

UIImage *image3 = [[array objectAtIndex:0] image];

看看这部分:
[array objectAtIndex:0] 

Objective-C 没有从这个方法调用返回的对象的类型信息,所以它的类型是 id .现在您要求发送 imageid 的消息.但是一个 id不是类型化对象。 Objective-C 是怎么做到这一点的?

基本上,它必须猜测您要发送的消息。因此,它通过其已知的 image方法,只挑一个。它知道六种这样的方法:

enter image description here

你说的是第四个。但碰巧编译器选择了第一个,它返回一个 CIImage。所以按照你的标准,它猜“错了”。但是你让它猜测,它必须猜测一些东西。

这正是您上一个示例中的 Actor 修复的问题:
UIImage *image4 = [(UIImageView *) [array objectAtIndex:0] image];

所以,道德:不要做你在 image3 中所做的事情。线。做你在 image4 中所做的事情线!你有编译器没有的类型信息:告诉编译器你知道什么。

(请注意,您编写代码的方式实际上并没有造成任何伤害。编译器警告只是:警告。实际上,当向 UIImageView 发送 image 消息时,将返回一个 UIImage 并且所有将很好。但是编译器警告你它不知道这一点。通过不强制转换,你已经放弃了所有静态类型并迫使编译器放手。编译器不知道会发生什么,所以它会发出警告你说这必须在运行时解决。当你转换时,你在编译时解决了这个问题。)

关于ios - Objective-C:NSMutableArray 的未转换元素返回意外类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36073256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com