How to implement the “didset of swift” in objective-c?

蓝咒 提交于 2019-12-10 12:31:51

问题


Swift (from the book 《iOS Animations by Tutorials:Chapter 12》 released by http://www.raywenderlich.com/):

let photoLayer = CALayer()

@IBInspectable
  var image: UIImage! {
    didSet {
      photoLayer.contents = image.CGImage
    }
}

How can I implement the above syntax in objective-c? I know only to set the property of photoLayer and image like below:

@property (strong, nonatomic) CALayer *photoLayer;
@property (strong, nonatomic) IBInspectable UIImage *image;

But i do not know how to implement didset{...} parts using objective-c syntax, please help!


回答1:


override the setter and implement the setter yourself.

- (void)setImage:(UIImage*)image {
    _image = image;
    photoLayer.contents = image.CGImage
}



回答2:


Swift needs special language features for this, because of its static nature, one cannot subclass at runtime.

In Objective-C this is not necessary, so you have no language feature for this. You can use key-value observation.

But if the observing instance is the instance whose property changed, you can do it with subclassing as mentioned by @Daij-Djan. (Basically this is what you do in Swift.) Additionally in Objective-C you have the ability to observe the properties of a different instance of a different class.



来源:https://stackoverflow.com/questions/32756344/how-to-implement-the-didset-of-swift-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!