在Swift中使用Cocoa的现有设计模式介绍

2020-01-08 22:35:44刘景俊

复制代码
var writeError : NSError?
let written = myString.writeToFile(path, atomically: false,
    encoding: NSUTF8StringEncoding,
    error: &writeError)
if !written {
    if let error = writeError {
        println("write failure: (error.localizedDescription)")
    }
}

 

当你实现自己的方法时,你需要配置一个 NSErrorPointer 对象,并将 NSErrorPointer 对象的 memory 属性设为你创建的NSError 对象。首先检查调用者传递的参数,确保它是一个非 nil 的 NSError 对象。
复制纯文本新窗口

复制代码
func contentsForType(typeName: String! error: NSErrorPointer) -> AnyObject! {
    if cannotProduceContentsForType(typeName) {
        if error {
            error.memory = NSError(domain: domain, code: code, userInfo: [:])
        }
        return nil
    }
    // ...
}

 

Target-Action模式(Target-Action)

当有特定事件发生,需要一个对象向另一个对象发送消息时,我们通常采用 Cocoa 的 Target-Action 设计模式。Swift 和 Objective-C 中的 Target-Action 模型基本类似。在 Swift 中,你可以使用 Selector 类型达到 Objective-C 中 selectors 的效果。请在Objective-C Selectors 中查看在 Swift 中使用 Target-Action 设计模式的示例。

类型匹配与统一规范(Introspection)

在 Objective-C 中,你可以使用 isKindOfClass: 方法检查某个对象是否是指定类型,可以使用 conformsToProtocol: 方法检查某个对象是否遵循特定协议的规范。在 Swift 中,你可以使用 is 运算符完成上述的功能,或者也可以使用 as? 向下匹配指定类型。

你可以使用 is 运算符检查一个实例是否是指定的子类。如果该实例是指定的子类,那么 is 运算结果为 true,反之为false。

复制代码
if object is UIButton {
    // object is of type UIButton
} else {
    // object is not of type UIButton
}

 

你也可以使用 as? 运算符尝试向下匹配子类型,as? 运算符返回不定值,结合 if-let 语句使用。