我遇到了最基本的客觀C方法問題。 基於以下建議: How can I truncate an NSString to a set length?iOS Objective C NSString.length不返回期望值
我想寫一個方法來返回截斷的NSString。但是,它不起作用。例如,當我發送「555」時,長度(如變量'test'所示)返回爲0.我通過在行int測試後面設置斷點並將鼠標懸停在變量fullString和test上來確定此位置。我是否需要將指針取消引用到fullString或其他某些東西?我是一個完整的新手在客觀C.非常感謝
-(NSString*) getTruncatedString:(NSString *) fullString {
int test = fullString.length;
int test2 = MIN(0,test);
NSRange stringRangeTest = {0, MIN([@"Test" length], 20)};
// define the range you're interested in
NSRange stringRange = {0, MIN([fullString length], 20)};
// adjust the range to include dependent chars
stringRange = [fullString rangeOfComposedCharacterSequencesForRange:stringRange];
// Now you can create the short string
NSString* shortString = [_sentToBrainDisplay.text substringWithRange:stringRange];
return shortString;
}
基於評論和研究,我得到它的工作。謝謝大家。如果有人有興趣:
-(NSString*) getTruncatedString:(NSString *) fullString {
if (fullString == nil || fullString.length == 0) {
return fullString;
}
NSLog(@"String length: %d", fullString.length);
// define the range you're interested in
NSRange stringRange = {MAX(0, (int)[fullString length]-20),MIN(20, [fullString length])};
// adjust the range to include dependent chars
stringRange = [fullString rangeOfComposedCharacterSequencesForRange:stringRange];
// Now you can create the short string
NSString* shortString = [fullString substringWithRange:stringRange];
return shortString;
}
「我是否需要將指針取消引用到fullString」 - 當然不是。你永遠不會對指向Objective-C對象的指針取消引用。 – 2013-01-05 16:49:20
你確定fullstring不是零嗎? –
什麼是_sentToBrainDisplay.text值? –