0

One question came into my mind today while working with objective c again after long time. Lets say I have following code for computed initializer that is written in swift 3.0.

private let loginButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = UIColor(hex: 0x0083C5, alpha: 1)
        button.setTitle("Login", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        button.layer.cornerRadius = 5
        return button
    }() 

Above code returns an instance of UIButton. How can I write same code in objective C?

Update: I already know the way of using Lazy Instantiation. Is there any other way from which I can create immutable instances?

appleBoy21
  • 632
  • 8
  • 23
  • 4
    A similar C construct is a "compound statement expression", see http://stackoverflow.com/questions/21909511/ios-name-of-this-way-of-building-and-returning-an-object-in-objective-c for an example. – Martin R Apr 24 '17 at 10:08
  • @MartinR - Can I use same stuff here? – appleBoy21 Apr 24 '17 at 10:12

1 Answers1

3

I use some thing like this

@interface TestClass : NSObject
@property (nonatomic, readonly) UIButton* button;
@end

@implementation TestClass
@synthesize button=_button;
-(UIButton*)button
{
  if (_button==nil) {
    _button = [UIButton buttonWithType:UIButtonTypeSystem];
    ...
  }
  return _button;
}

@end
Sergey
  • 1,589
  • 9
  • 13