Spanky
Spanky

Reputation: 5000

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_ACCESS".

from gdb.

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

Any help appreciated // :)

Upvotes: 7

Views: 32039

Answers (6)

Tim Windsor Brown
Tim Windsor Brown

Reputation: 4089

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

So:

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

Upvotes: 2

Alok Srivastava
Alok Srivastava

Reputation: 197

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

`

Upvotes: 2

user1481723
user1481723

Reputation:

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

Upvotes: 0

NSResponder
NSResponder

Reputation: 16861

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.

Upvotes: 1

BitDrink
BitDrink

Reputation: 1193

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.

Upvotes: 17

duncanwilcox
duncanwilcox

Reputation: 3498

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.

Upvotes: 0

Related Questions