Append a newline to an NSString

删除回忆录丶 提交于 2019-12-06 00:39:27

问题


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 // :)


回答1:


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.




回答2:


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

`




回答3:


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

So:

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



回答4:


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.




回答5:


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.




回答6:


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



来源:https://stackoverflow.com/questions/1699678/append-a-newline-to-an-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!