【问题标题】:Why Class<type> produces warning and Class not, when using with alloc, init为什么 Class<type> 在与 alloc、init 一起使用时会产生警告而 Class 不会
【发布时间】:2013-07-05 11:13:32
【问题描述】:

我有两段代码:

for(Class<ContactV2Storage> tmpClass in config->ctxStorageClasses){
    id<ContactV2Storage> stor = [[[tmpClass alloc] init] autorelease];
}

for(Class tmpClass in config->ctxStorageClasses){
    id<ContactV2Storage> stor = [[[tmpClass alloc] init] autorelease];
}

两者的工作原理相同,但在使用第一个版本(我认为更好)时,编译器会给我一个警告:

Class method '+alloc' not found (return type defaults to 'id')

我很好奇为什么会这样?

【问题讨论】:

    标签: objective-c alloc


    【解决方案1】:

    Class 类型表示一个 Objective-C 类(它是一个 C 结构)。请参阅运行时文档here

    只有Class定义 可以符合协议(您可以检查class_conformsToProtocolNSObjectconformsToProtocol:)。所以你的第一段代码使用Class&lt;ContactV2Storage&gt;是不正确的。

    第二部分大部分是正确的,但更安全的方法是:

    for(Class tmpClass in config->ctxStorageClasses) {
        if([tmpClass conformsToProtocol:@protocol(ContactV2Storage)]) {
            id<ContactV2Storage> stor = [[[tmpClass alloc] init] autorelease];
            // do stuffs
        }
    }
    

    这样您就可以确定您正在实例化的类遵守协议并且可以安全地接收您发送的任何消息。如果协议中的任何方法是可选的,您还应该在调用它们之前检查实例化对象(在本例中为stor)是否响应它们,否则应用程序将崩溃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 2011-01-16
      • 2015-12-03
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      相关资源
      最近更新 更多