Dave
Dave

Reputation: 8641

iOS Objective C NSString.length not returning expected value

I'm having the most basic of problems with an objective C method. Based on a suggestion from: How can I truncate an NSString to a set length?

I am trying to write a method to return a truncated NSString. However, it is not working. When I send in "555" for example, the length (as shown by the variable 'test') comes back as 0. I determined this by setting a break point after the line int test and hovering over the variables fullString and test. Do I somehow need to dereference the pointer to fullString or some other thing? I am a complete newbie in objective C. Many thanks

-(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;

}

Based on comments and research, I got it working. Thank you everyone. In case anyone is interested:

-(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;

}

Upvotes: 0

Views: 4007

Answers (1)

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

Check if you are passing @"555" to this method, not "555". Also, better way is to

NSLog(@"String length: %d", fullString.length).

Upvotes: 1

Related Questions