Swift 设计模式 KVO Block

955 阅读1分钟

KVO 在Swift中的使用方式

var currentIndex:NSInteger = 0

报错:forKeyPath:@"currentIndex" was sent to an object that is not KVC-compliant for the "currentIndex" property.'

KVO监听属性currentIndex出现crash:

在Swift中使用KVO,我们必须把对象用 @objc 和 dynamic同时修饰。如下所示:

  @objc dynamic var currentIndex:NSInteger?
    self.addObserver(self, forKeyPath: "currentIndex", options: [.new,.initial], context: nil)

然后才能观察到该属性值得变化

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
       if keyPath == "currentIndex" {
           //todo:what you want 
           
       }
   }

Block 在Swift中的使用方式

///Swift定义闭包
typealias MusicCellPlayBlock = (Int) -> ()
typealias MusicCellBlock = () -> ()
class KKVideoPlayCell: UITableViewCell {
   open var musicPlayBlock: MusicCellPlayBlock!
   open var musciCellBlock: MusicCellBlock!
}
    cell.musicPlayBlock = {(tag: Int) -> () in
        print("tag is :\(tag)")
    }
    cell.musciCellBlock = {() -> () in
        
    }

Objective-C定义Block

typedef void (^MusicCellPlayBlock)(void);
typedef void(^MusicCellBlock)(NSInteger index);

@interface KKVideoPlayCell : UITableViewCell

@property (nonatomic, copy)MusicCellPlayBlock musicPlayBlock;
@property (nonatomic, copy)MusicCellBlock musciCellBlock;

@end

单例对比

//单例
+ (KKDownLoader *)shared{
    static dispatch_once_t once;
    static KKDownLoader *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [KKDownLoader new];
    });
    return instance;
}

class KKCacheManager {
    static let shared = KKCacheManager()
    private init() {}

}