Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is my NSRange always 0?
    text
    copied!<p>I want to implement a delete key for my calculator app. My pseudocode for this was:</p> <pre><code>foo = length of current number bar = length of current number-1 current number = current number with character at index (foo-bar) removed </code></pre> <p>To do this in objective-c I have tried to implement this using the NSRange function as well as the StringbyappendingString method:</p> <pre><code>- (IBAction)DelPressed { if ([self.display.text length] &gt;=2) { int len = [self.display.text length];//Length of entire display //Add to the brainlong printing out the length of the entire display self.brainlog.text = [NSString stringWithFormat:@"Len is %g",len]; int le = ([self.display.text length]-1);//Length of entire display - 1 NSString *lestring = [NSString stringWithFormat:@"LE is %g",le]; //Add to the brainlog printing out the length of the display -1 self.brainlog.text = [self.brainlog.text stringByAppendingString:lestring]; NSRange range = NSMakeRange(le, len);//range only includes the last character self.display.text = [self.display.text stringByReplacingCharactersInRange:range withString:@" "];//Replace the last character with whitespace } </code></pre> <p>The output to brainlog (ie the length of both le and len) is:</p> <pre><code>Len is -1.99164 Le is -1.99164 </code></pre> <p>Hard to see, but here's an image of the number I input to the calculator using the iOS simulator: <img src="https://i.imgur.com/11AyF.png" alt="iOS sim picture"></p> <p>I have tried to change the value of le (ie making it the length of the display -3 or -5 etc) and both le and len are still the same.</p> <p>I have also tried to make le in reference to len:</p> <pre><code> int len = [self.display.text length];//Length of entire display //Add to the brainlong printing out the length of the entire display self.brainlog.text = [NSString stringWithFormat:@"Len is %g",len]; int le = len-1; </code></pre> <p>But the values of the two are still the same. How can I use NSRange to delete the last character of the display?</p> <p><strong>Edit</strong>: Using Dustin's fix, I now have reduced a rather lengthy function into 6 lines of code:</p> <pre><code> -(IBAction)DelPressed{ if ([self.display.text length] &gt;=2) { self.display.text = [self.display.text substringToIndes:[self.display.text length] -1]; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload