Need help with stringByAppendingFormat

In the code snippet below, I create a NSString, list each character one by one, and then try to recreate the NSString using the stringByAppendingFormat instance method.

    //  Listing characters in a string experiment
    NSString *newString = @"Keith R Jones";
    NSString *copiedString;
    for (int i = 0; i < [newString length]; i++) {
        NSLog(@"   %c\n", [newString characterAtIndex:i]);
        copiedString = [copiedString stringByAppendingFormat:
                        @"%c",[newString characterAtIndex:i]];
    }
    NSLog(@"\n%@\n\n", copiedString);

As you can see in the console output below, the listing of characters works fine but recreating the NSString doesn’t. When I try to print the recreated NSString, I get (null).

2015-07-21 09:35:17.837 Chapter16Experiments[2498:303] K
2015-07-21 09:35:17.837 Chapter16Experiments[2498:303] e
2015-07-21 09:35:17.838 Chapter16Experiments[2498:303] i
2015-07-21 09:35:17.838 Chapter16Experiments[2498:303] t
2015-07-21 09:35:17.838 Chapter16Experiments[2498:303] h
2015-07-21 09:35:17.839 Chapter16Experiments[2498:303]
2015-07-21 09:35:17.839 Chapter16Experiments[2498:303] R
2015-07-21 09:35:17.839 Chapter16Experiments[2498:303]
2015-07-21 09:35:17.839 Chapter16Experiments[2498:303] J
2015-07-21 09:35:17.840 Chapter16Experiments[2498:303] o
2015-07-21 09:35:17.840 Chapter16Experiments[2498:303] n
2015-07-21 09:35:17.840 Chapter16Experiments[2498:303] e
2015-07-21 09:35:17.841 Chapter16Experiments[2498:303] s
2015-07-21 09:35:17.841 Chapter16Experiments[2498:303]
(null)

Help much appreciated

I also tried declaring copiedString as an NSMutableString and using the appendFormat method. It didn’t work. The output was the same.

    //  Listing characters in a string experiment
    NSString *newString = @"Keith R Jones";

// NSString *copiedString;
NSMutableString *copiedString;
for (int i = 0; i < [newString length]; i++) {
NSLog(@" %c\n", [newString characterAtIndex:i]);
// copiedString = [copiedString stringByAppendingFormat:
// @"%c",[newString characterAtIndex:i]];
[copiedString appendFormat:@"%c", [newString characterAtIndex:i]];
}
NSLog(@"\n%@\n\n", copiedString);

Your crime: sending messages to a nil object :slight_smile:

You must initialise the copiedString with a string object first before entering the for statement. If you don’t, you will be sending messages to a nil object only to get back another nil object.

Compare:

// Listing characters in a string experiment
NSString *newString = @"Keith R Jones";

NSString *copiedString = [NSString string];

for (int i = 0; i < [newString length]; i++) {
     NSLog(@" %c\n", [newString characterAtIndex:i]);
     copiedString = [copiedString stringByAppendingFormat: @"%c", [newString characterAtIndex:i]];
}
NSLog (@"\n%@\n\n", copiedString);

[Become a competent programmer: pretty-function.org]

“Your crime: sending messages to a nil object :slight_smile:” -> I plead guilty

thanks for the help