为什么我的NSRange总是0?
我想为我的计算器应用程序实现一个删除键。 我的伪代码是这样的:
foo = length of current number bar = length of current number-1 current number = current number with character at index (foo-bar) removed
要在objective-c中做到这一点,我试图用NSRange函数以及StringbyappendingString方法实现这个:
- (IBAction)DelPressed { if ([self.display.text length] >=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 }
brainlog的输出(即le和len的长度)是:
Len is -1.99164 Le is -1.99164
很难看,但这里是我使用iOS模拟器input到计算器的数字的图像:
我试图改变乐的价值(即使它的显示长度-3或-5等),le和len都是一样的。
我也曾试图在le参照len:
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;
但是两者的价值还是一样的。 我如何使用NSRange来删除显示的最后一个字符?
编辑 :使用达斯汀的修复,我现在已经减less了一个相当冗长的function成6行代码:
-(IBAction)DelPressed{ if ([self.display.text length] >=2) { self.display.text = [self.display.text substringToIndes:[self.display.text length] -1]; } }
使用substring
代替; 如果你想要做的是删除最后一个字符,那就好多了。
更具体地说, substringToIndex(/*length-1*/)
如果你需要用string做其他事情,请检查这个参考