【发布时间】:2013-01-05 16:43:29
【问题描述】:
我在使用客观 C 方法时遇到了最基本的问题。 根据以下建议: How can I truncate an NSString to a set 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;
}
基于 cmets 和研究,我得到了它的工作。谢谢大家。如果有人感兴趣:
-(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 中,你永远不会取消引用指向对象的指针。
-
你确定 fullstring 不是 nil 吗?
-
什么是_sentToBrainDisplay.text 值?
-
这整个函数看起来一团糟……
-
@Dave - 这有点令人困惑。 Stack Overflow 未设置为回答问题块中的问题。您在下面接受了 Nickolay 的回答,然后您编辑了您的问题以发布其他人的答案。它是哪一个?您应该从问题中删除您的答案并将其放在答案块中。您应该解释解决方法(我已经看过两次,对我来说并不明显),然后您应该接受您的答案。
标签: objective-c ios xcode