objc_sync同步需要注意的坑

objc_sync_enter(obj); defer { objc_sync_exit(obj) } 可以用来同步一个方法,但是需要注意这里的obj在函数执行过程中可能会发生变化。比如下面方法

    private func sync(_ obj:Any, action:(()->T)) -> T{
        objc_sync_enter(obj)
        NSLog("the sync obj enter :\(Unmanaged.passUnretained(obj as AnyObject).toOpaque()) self:\(Unmanaged.passUnretained(self).toOpaque())")
        let t = action()
        objc_sync_exit(obj)
        NSLog("the sync obj exit :\(Unmanaged.passUnretained(obj as AnyObject).toOpaque()) self:\(Unmanaged.passUnretained(self).toOpaque())")
        
        return t
    }

在执行完成let t = action()其实obj有可能发生变化,打印日志如下:

2019-03-09 17:04:47.122516+0800 Shelf[6725:585195] the sync obj enter :0x000000010f81b120 self:0x0000000107e14c90
2019-03-09 17:04:47.123046+0800 Shelf[6725:585195] the sync obj exit :0x0000000104199290 self:0x0000000107e14c90

你可能感兴趣的:(objc_sync同步需要注意的坑)