Copy

2018-05-10  本文已影响4人  流年易逝_李

在swift中,NSObject的子类可以使用copy方法来复制实例对象,做法如下:

子类必须声明并实现NSCopying协议;

子类实现copyWithZone:方法;

子类的构造方法init必须使用requried关键字修饰

示例代码:

class ClazzA:NSObject,NSCopying {

     var memberA = 0

     // 必须使用required关键字修饰

      required override init() {   

      }

      // 实现copyWithZone方法

      func copyWithZone(zone: NSZone)->AnyObject {

             let theCopyObj = self.dynamicType.init()        

             theCopyObj.memberA = self.memberA

             return theCopyObj    

      }

}

extension MTLCLFrame : NSCopying, NSMutableCopying {

    public func copy(with zone: NSZone? = nil) -> Any {

        let frame = MTLCLFrame()

        frame.currentSampleTime = self.currentSampleTime

        frame.orientation = self.orientation

        frame.sampleBuffer = self.sampleBuffer

        frame.image = self.image

        MTLog(message: self.image)

        MTLog(message: frame.image)

        frame.sourceType = self.sourceType

        frame.parameters = self.parameters

        return frame

    }

    public func mutableCopy(with zone: NSZone? = nil) -> Any {

        let frame = MTLCLFrame()

        frame.currentSampleTime = self.currentSampleTime

        frame.orientation = self.orientation

        frame.sampleBuffer = self.sampleBuffer

        frame.image = self.image

        frame.sourceType = self.sourceType

        frame.parameters = self.parameters

        return frame

    }

}

let currentFrame = frame.copy()

上一篇 下一篇

猜你喜欢

热点阅读