开发者

NSString stringWithUTF8String appending error

I'm trying to append a char array to an NSString. When I use the code below, I get this error:

********* initializat开发者_C百科ion 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];


I think you're looking for something like this:

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜