1

How to protect this method by checking to see if the segmentedControl and its superview exist before setting the frame?

- (void)setSegmentedControlFrame {
    self.segmentedControl.frame = CGRectMake(CGRectGetMinX(self.segmentedControl.superview.frame), CGRectGetMinY(self.segmentedControl.superview.frame), CGRectGetWidth(self.segmentedControl.superview.frame), CGRectGetHeight(self.segmentedControl.superview.frame));
}
dicle
  • 1,122
  • 1
  • 12
  • 40

2 Answers2

0

Do like this

- (void)setSegmentedControlFrame {
   if self.segmentedControl.isDescendantOfView(self.view)
   {
      self.segmentedControl.frame = CGRectMake(CGRectGetMinX(self.segmentedControl.superview.frame), CGRectGetMinY(self.segmentedControl.superview.frame), CGRectGetWidth(self.segmentedControl.superview.frame), CGRectGetHeight(self.segmentedControl.superview.frame));
   }

}
Irfan Gul
  • 1,579
  • 13
  • 23
  • That would work in objective-c but does not check explicitely self.segmentedControl for being null or not. It works because sending any method to null returns null or 0 or false respectively. So the assignment will not be executed when self.segementedControl is null. However, I doubt this is considered clean code. – Hermann Klecker Nov 11 '15 at 10:25
  • exactly, this is cleaner and nice. – Irfan Gul Nov 11 '15 at 10:28
0
if ((self.segmentedControl) && (self.segmentedControl.superview)) {
   // do something smart here. 
}

The inner brackets are not really required. To be more specific:

if ((self.segmentedControl != null) && (self.segmentedControl.superview != null)) {
   // do something smart here. 
}

When the first condidtion of a && is checked and evaluates to false then the second is not exceuted any more. In other langauges, where accessing null objects is more of a problem, this sequence is important.

Is this what you have asked for?

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71