What are the best practices for refactoring methods in Objective-C

65 Views Asked by At

How can I get this kind of method refactored better?
This is just a sample in my objective-c project, and I am trying to do it all programmatically
Im not sure what the best practices would be, create a protocol? an extension? or refactor further down to additional methods?

- (void)viewDidLoad {
    [super viewDidLoad];
    // Label to be changed
    label = [[UILabel alloc]init];
    label.text = @"Changed with code!";
    [self.view addSubview:label];
    // Label Constraints
    label.translatesAutoresizingMaskIntoConstraints = NO;
    [label.topAnchor constraintEqualToAnchor: self.view.safeAreaLayoutGuide.topAnchor constant:50].active = YES;
    [label.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor constant:20].active = YES;
    [label.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor constant:-20].active = YES;
}
1

There are 1 best solutions below

0
storoj On

As an example you could create a UIView subclass that creates the label and makes the layout.

@interface MyView: UIView
@property (nonatomic, strong, readonly) UILabel *label;
@end

@interface ViewController: UIViewController
@property (nonatomic, strong, readonly) MyView *myView;
@end

@implementation MyView

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    _label = [[UILabel alloc] initWithFrame:CGRectZero];
    _label.translatesAutoresizingMaskIntoConstraints = NO;

    UILayoutGuide *safeAreaLayoutGuide = self.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
      [label.topAnchor constraintEqualToAnchor: safeAreaLayoutGuide.topAnchor constant:50],
      [label.leadingAnchor constraintEqualToAnchor:safeAreaLayoutGuide.leadingAnchor constant:20],
      [label.trailingAnchor constraintEqualToAnchor:safeAreaLayoutGuide.trailingAnchor constant:-20]
    ]];
  }
  return self;
}

@end

@implementation MyViewController

- (void)loadView {
  self.view = [[MyView alloc] initWithFrame:CGRectZero];
}

- (MyView *)myView {
  return (id)self.view; // it makes view to load regardless which
                        // property do you use – `view` or `myView`
}

- (void)viewDidLoad {
  [super viewDidLoad];

  self.myView.label.text = @"Changed with code!";
}

@end