我想爲我的計算器應用程序實現一個刪除鍵。我對這個僞代碼爲:爲什麼我的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(即這兩個文件和len)的長度爲:
Len is -1.99164 Le is -1.99164
很難看到,但這裏的數字I輸入使用的iOS模擬器計算器的圖像:
我試圖改變樂的價值(即使它的顯示長度-3或-5等),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刪除顯示的最後一個字符?
編輯:使用達斯汀的修復,我現在已經減少了一個相當長的功能分爲6行代碼:
-(IBAction)DelPressed{
if ([self.display.text length] >=2)
{
self.display.text = [self.display.text substringToIndes:[self.display.text length] -1];
}
}
%G也是double類型的格式說明,請嘗試使用%d爲int型。 – adc 2012-07-19 18:33:29
「brainlog」究竟是什麼?也許我錯過了一些東西,但是看起來這裏的真正問題與'NSRange'沒有任何關係,而應該是關於如何將字符串的長度存儲爲int並以負浮點數結尾代替。你有沒有嘗試過使用NSLog(@「len是%d」,len)'來驗證'len'的值? – 2012-07-19 18:39:44
'brainlog'只是另一個'UILabel',用於記錄已被按下的操作符以及數字。在這種情況下,我將它用作打印語句以查看我的方法出了什麼問題。我已經嘗試了NSlog的方式,並得到了相同的結果,總是一些浮動... – ironcyclone 2012-07-19 18:45:32