How to implement the "didset of swift" in objective-c?
Asked Answered
J

2

25

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!

Jephthah answered 24/9, 2015 at 8:5 Comment(4)
check this...#26674611Pinchas
please not this will crash in swift if image is nil.Roseroseann
in objc calling a nil object works, but in swift it could be photoLayer.contents = image != nil ? image.CGImage : nilRoseroseann
it looks you look for the -setImage: method.Extroversion
R
45

override the setter and implement the setter yourself.

- (void)setImage:(UIImage *)image {
    if (_image != image) {
        _image = image;
        photoLayer.contents = image.CGImage;
    }
}
Roseroseann answered 24/9, 2015 at 8:13 Comment(0)
R
3

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.

Rozamond answered 24/9, 2015 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.