iphone - 快速枚举在objective-c中没有给出正确的对象类型?

标签 iphone ios objective-c

我觉得这很奇怪。所以我有一个 UIView我想更改 textcolor全部UILabel .这是我所做的:

for (UILabel *label in [self subviews]) { // self is the UIView
    label.textColor = someColor;
}

当我运行代码时,它崩溃了,像 UIImageView: unrecognized selector setTextColor: sent to instance (some instance) 这样的错误

所以看来 label在快速枚举中其实是一个UIImageView .顺便说一句,我确实有两个 UIImageView s 在 UIView *self .但是,快速枚举不应该只给出UILabel吗?仅(因为我指定了 UILabel *label 而不是 UIView *label )?

我认为这是问题所在,因为当我编写以下代码时,它可以工作。
for (UILabel *label in [self subviews]) { // self is the UIView
    if ([label isKindOfClass:[UILabel class]]) {
        label.textColor = someColor;
    }
}

所以在这段代码中,当我检查以保证 labelUILabel然后设置它的textcolor , 所有 UILabel View 中的 s 正确地改变了它们的颜色。

谁能解释我为什么需要 if-statement仔细检查实例类型?

最佳答案

您的 2 个循环非常不同。第一个假设所有 subview 都是标签,第二个检查每个 subview 以确保它是一个标签。第一个也应该检查。

快速枚举基本上是语法糖,只是普通的for环形。它不会神奇地过滤或操作您给它枚举的列表。

关于iphone - 快速枚举在objective-c中没有给出正确的对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18043971/

相关文章:

iphone - 进入后台取消剩余请求

ios - Swift Json Tableview 滞后

ios - 所需条件为假 : IsFormatSampleRateAndChannelCountValid(hwFormat)

Objective-C,定期在后台运行 NSTask

iphone - MKMapView 设置区域

iphone - 将 GMT 时间转换为本地时间

ios - 裁剪图像的图像裁剪问题

iphone - 应用程序未主动运行作业,怎么办?

objective-c - UIImageView 填充 UIView

iphone - 插入新行时 UITableViewCell 按钮未获取标记