重新分配后NSString变量值消失

时间:2012-06-28 19:35:57

标签: iphone objective-c ios cocoa-touch nsstring

有些奇怪的事情正在发生。当我将NSString重新分配给我的代码底部附近的subString变量时。看来subString的值在输出中是空的。我不知道objectAtIndex是否返回奇怪的东西或者是内存问题。如果我创建一个新变量而不是重新分配subString的值,我可以打印输出控制台中的正确值。如果有人能帮我解决这个问题。非常感谢。

NSString *subString = @"";
if ([text length] > 0) 
{
    UITextRange *selectedRange = [_textView selectedTextRange];
    UITextPosition *cursorPosition = [_textView positionFromPosition:selectedRange.start offset:0];
    UITextRange *subTextRange = [_textView textRangeFromPosition:_textView.beginningOfDocument toPosition:cursorPosition];
    subString = [textView textInRange:subTextRange];
}

NSLog(subString);
NSLog(@" %s", [subString hasSuffix:@" "] ? "TRUE" : "FALSE");
BOOL hasSpaceSuffix = [subString hasSuffix:@" "];
NSLog(@" %s", _taggingInProgress ? "TRUE" : "FALSE");
NSArray *substringArray = [[subString componentsSeparatedByString:@" "] retain];
if ([substringArray count] > 1) {
    int index = [substringArray count];
    if ([[substringArray objectAtIndex:index-1] isEqualToString:@" "])
    {
        NSLog(@"1st");
        subString = [substringArray objectAtIndex:index-2];
        NSLog(subString);
    }
    else
    {
        NSLog(@"2nd");
        subString = [substringArray objectAtIndex:index-1];
        NSLog(subString);
    }
    NSLog(@"AFTER");
    NSLog(subString);
}

1 个答案:

答案 0 :(得分:0)

我认为您需要使用:

subString = [NSString stringWithString:[substringArray objectAtIndex:index]];

...固定...