Pitfall of Using String Length as Boolean in Objective-C

As I pointed out in last two posts, I will give one example of how the pitfal of using string length as boolean looks like.

The example is simple, I want to enable the button when the user begins typing in the textview.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  self.textView1.delegate = self;
  self.textView2.delegate = self;

  self.button1.enabled = NO;
  self.button2.enabled = NO;

  UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
  [self.view addGestureRecognizer:tapGesture];
}


- (void)hideKeyboard {
  if ([self.textView1 isFirstResponder]) {
    [self.textView1 resignFirstResponder];
  }
  else {
    [self.textView2 resignFirstResponder];
  }
}

- (void)textViewDidChange:(UITextView *)textView {
  if ([textView isEqual:self.textView1]) {
    self.button1.enabled = [textView.text length];
  }
  else {
    self.button2.enabled = [textView.text length] > 0;
  }
}

@end

As you see, there are two textviews and two buttons. The first button will be enabled by evaluating
self.button1.enabled = [textView.text length]; and the second will be enabled by evaluating
self.button2.enabled = [textView.text length] > 0; This looks like both should work fine, but no. The first one won’t work as expected and this is the pitfal that some people miss in there code.

Download full example and see the result with your own eyes here.

Comments