【问题标题】:Generics and delegate and Nullablity related code泛型和委托以及 Nullablity 相关代码
【发布时间】:2015-08-10 14:47:19
【问题描述】:

谁能解释一下这段代码是什么意思?这样的代码是一个很好的编码实践吗? MyProtocolOtherProtcol 是一些协议方法。这里的NSObject是什么意思?

@interface MYViewController () {

    NSObject<MyProtocol> * abc;
    NSObject<OtherProtcol> * def;

}

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    这个类有 2 个属性可以接受任何对象(NSObject 的子类)并且必须符合 MyProtocolOtherProtocol

    示例:

    @interface SomeClass {
    }
    
    myViewController.abc = [SomeClass new]; // error this class does not conform to MyProtocol 
    
    @interface AnotherClass<MyProtocol> {
    }
    
    myViewController.abc = [AnotherClass new]; // works
    myViewController.def = [AnotherClass new]; // error AnotherClass does not conform to OtherProtocol
    

    这是新的面向协议的编程,您应该大量使用它而不是子类化。使用 swift 检查 wwdc 面向协议的编程

    【讨论】:

    • 为什么我们需要 NSObjecct 通常我们曾经有 id 并且将它们设为此类的属性不是一个好主意吗?
    • id 可以是任何类型,也可以是任何对象,在 swift (structs, Int) 中会被翻译为 AnyObject。 NSObject 实现了复制,因此您可以将其添加到字典中。而且在swift中,一些值类型可以符合不能暴露给objc的协议,所以在这种情况下你可以保护你自己
    • 这两个属性可能应该用id而不是NSObject来声明,除了特定的协议。协议应该扩展NSObject 协议(不要与NSObjet 类混淆)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    相关资源
    最近更新 更多