我在使用客观 C 方法时遇到了最基本的问题。基于来自的建议: 如何将 NSString 截断为设定的长度?
我正在尝试编写一种方法来返回截断的 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;
}