简体   繁体   中英

NSString Variable Value disappearing after reassignment

Something strange is going on. When I reassign an NSString to my subString variable near the bottom of my code. It seems that the value of subString is empty in the output. I don't know if objectAtIndex is returning something weird or it's a memory problem. If I create a new variable instead of reassigning the value of subString, I can print see the correct value in the output console. If anyone could help me figure this out. It'd be greatly appreciated.

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);
}

I think you need to use:

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

...fixed...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM