【问题标题】:fast enumeration for array containing different types of objects包含不同类型对象的数组的快速枚举
【发布时间】:2009-08-12 11:33:58
【问题描述】:

如果我有一个 NSMutableArray,我在其中添加了不同类的对象(例如 NSString、NSMutableString、NSProcessInfo、NSURL、NSMutableDictionary 等)现在我想快速枚举这个数组,所以我尝试了:

for (id *element in mutableArray){
   NSLog (@"Class Name: %@", [element class]);
   //do something else
}

我在 Xcode 中收到警告说

warning: invalid receiver type "id*"

我怎样才能避免这个警告?

【问题讨论】:

    标签: objective-c fast-enumeration


    【解决方案1】:

    代码几乎是正确的。当你使用 id 时,它已经被暗示为一个指针,所以你应该把它写成:

    for (id element in mutableArray){
       NSLog (@"Class Name: %@", [element class]);
       //do something else
    }
    

    【讨论】:

    • 你也可能想要[element className]而不是[element class]
    • well class 也可以正确打印出名称,但是 className 在阅读代码时更有意义...感谢您的提示!
    • 其实 -className 并不是为了这个目的。该方法用于 Cocoa 中的脚本集成。 -[Class description] 应该提供正确的结果,但如果你想学究气,NSStringFromClass([element class]) 更正确
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多