开发者

Append a newline to an NSString

I have this:

if (soapResults != nil) {
    soapResults = [soapResults stringByAppendingString:@"\n"];
    }

But I get a warning:

Assignment from distinct Objective-C type on build.

When I run it on device I get:

Program received signal: "EXC_BAD_AC开发者_开发问答CESS".

from gdb.

Any ideas how to append a newline to an NSString without getting a warning or error?

Any help appreciated // :)


An alternative is: [NSString stringWithFormat: @"%@\n", soapResults] even if the logic is the same!

However, even in the case of stringByAppendingString, it returns a new string but it doesn't change the target, so you have to assign the new string to a new instance of the class NSString.


You can try this, it works for me:

NSString *content1 = [messageObject valueForKey:@"content"];
NSString *seprator = @"\n----------------------\n";
NSString *myString = [NSString stringWithFormat:@"%@\n%@\n",seprator,content1];
content = [content stringByAppendingString:myString];

`


I've found \r works better than \n when using NSStrings.

So:

NSString *stringWithNewLine = [soapResults stringByAppendingString:@"\r"];


The object you get back from -stringByAppendingString: is autoreleased. You have to retain it if you want it to persist. If you don't retain it, you'll get a memory exception the next time you try to access it.

An easy way to make sure this happens is to declare "soapResults" as a property, and synthesize accessors for it.


You are likely to have memory management issues, soapResults is probably a stray pointer to an object that has been deallocated. Hard to say without seeing more code, but checking where the object has been originally allocated is a good start.

For example if it has been allocated via a [NSString stringWith... ] call then it is autoreleased by default, i.e. it will be released at the end of the run loop and you have to retain it if you want to hold on to it.


You are using forward slash , thats means it will be ignoring n, so basically you are appending nothing. I believe that may be a problem

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜