Objective c iOS目标NSC NSString.length未返回预期值

Objective c iOS目标NSC NSString.length未返回预期值,objective-c,ios,xcode,Objective C,Ios,Xcode,我有一个目标C方法的最基本的问题。 根据以下方面的建议: 我正在尝试编写一个方法来返回截断的NSString。然而,它不起作用。例如,当我发送“555”时,长度(如变量“test”所示)返回为0。我通过在int-test行之后设置一个断点并将鼠标悬停在变量fullString和test上来确定这一点。我是否需要取消对fullString指针的引用,或者其他什么?我是目标C的新手。非常感谢 -(NSString*) getTruncatedString:(NSString *) fullStri

我有一个目标C方法的最基本的问题。 根据以下方面的建议:


我正在尝试编写一个方法来返回截断的NSString。然而,它不起作用。例如,当我发送“555”时,长度(如变量“test”所示)返回为0。我通过在int-test行之后设置一个断点并将鼠标悬停在变量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;

}

检查是否将
@“555”
传递给此方法,而不是
“555”
。 另外,更好的方法是


NSLog(@“字符串长度:%d”,fullString.length)

“我是否需要取消对fullString指针的引用”-当然不需要。您从未取消对Objective-C中对象的指针的引用。您确定fullstring不是nil吗?什么是_sentToBrainDisplay.text值?整个函数看起来一团糟…@Dave-这有点令人困惑。堆栈溢出未设置为回答问题块中的问题。您接受了下面Nickolay的答案,然后编辑了您的问题,为其他人发布了答案。是哪一个?你应该从问题中删除答案,并将其放在答案栏中。你应该解释一下修复方法(我已经看过两次了,我看不清楚),然后你应该接受你的答案。感谢Nockolay对NSLog的评论。这一点,再加上拉米对屏幕显示的评论,让我想到了这个问题。我已经在原始问题中发布了解决方案,供稍后查看此问题的任何人使用。