我遇到了最基本的客观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值? –