tags:

views:

67

answers:

3

I'm trying to append a char array to an NSString. When I use the code below, I get this error: * initialization method -initWithCharactersNoCopy:length:freeWhenDone: cannot be sent to an abstract object of class NSCFString: Create a concrete instance!

What does this mean and how can it be fixed?

NSString *str =  [[NSString new] initWithString:@"Name: "];
NSString *name = [[NSString new] stringWithUTF8String:user.name];
//NSString *name = [[NSString stringWithUTF8String:seg.segname] copy]; //this also failed
str = [str stringByAppendingString:name];
A: 

I think you're looking for something like this:

NSString *str = @"Name: ";
NSString *name = [NSString stringWithUTF8String:user.name];
str = [str stringByAppendingString:name];
Carl Norum
A: 

Instead of appending a string to the other, I would use [NSString stringWithFormat:].

NSString *name = [NSString stringWithUTF8String:user.name];
str = [NSString stringWithFormat: @"Name: %@", name];

You can even write the code in a single line.

str = [NSString stringWithFormat: @"Name: %@", [NSString stringWithUTF8String:user.name]];
kiamlaluno
A: 

The error you are seeing is from sending -initWithString: to an already init'd string. This is because [NSString new] returns a string that is already initialized. You can't use +new if you need a special init method.

  1. For the -initWithString: message you need to alloc the NSString. This is the line causing the exception error and nothing afterwards is being executed. However, as Carl pointed out, you don't need to create another object for the name, @"Name: " is already an NSString.

  2. The +stringWithUTF8String: method is a class method so send it to the NSString class directly.

You may want to review Apple's objective-c documentation on Allocating and Initializing Objects.

Nathan Kinsinger