NSMutableString *a = @"Hi";
NSMutableString *b =[a stringByAppendingString:@"\n\n Hi Again"];
以上内容并未给出错误,但未在下一行显示“Hi Again”。为什么呢?
答案 0 :(得分:1)
EDIT2 我在发帖后意识到,OP在标题中有NSString但在代码中放了NSMutableString。我已经提交了一个编辑来将NSMutableString更改为NSString。
我会留下这个,因为它仍然有用。
我很惊讶没有给出错误,因为你给NSMtringString一个NSString。
您需要阅读NSMutableStrings上的文档。
给你一个想法
//non mutable strings
NSString *shortGreetingString = @"Hi";
NSString *longGreetingString = @"Hi Again";
/*mutable string - is created and given a character capacity The number of characters indicated by capacity is simply a hint to increase the efficiency of data storage. The value does not limit the length of the string
*/
NSMutableString *mutableString= [NSMutableString stringWithCapacity:15];
/*The mutableString, now uses an appendFormat to construct the string
each %@ in the Parameters for the appendFormat is a place holder for values of NSStrings
listed in the order you want after the comma.
Any other charactars will be included in the construction, in this case the new lines.
*/
[mutableString appendFormat:@"%@\n\n%@",shortGreetingString,longGreetingString];
NSLog (@"mutableString = %@" ,mutableString);
[pool drain];
答案 1 :(得分:1)
我认为 this 可能会对您有所帮助。你宁愿用'\ r'代替'\ n'
我也有类似的问题,发现 \ n 在LLDB中有效但在GDB中无效
答案 2 :(得分:0)
尝试使用NSString
。你可以使用:
NSString *a = [NSString stringWithFormat:@"%@\n\n%@", @"Hi", @"Hello again"]
答案 3 :(得分:0)
第一个@“Hi”是一个常数。它不能变异。即使指针显示它是NSMutableString,实际对象仍然是常量。
要创建NSMutableString对象,您需要执行例如[NSMutableString stringWithString:@"Hi"]
。
同样stringByAppendingString:
返回一个不可变的NSString,而不是一个可变的字符串。
您的代码应为(1):
NSMutableString *a = [NSMutableString stringWithString:@"Hi"];
NSString *b = [a stringByAppendingString:@"\n\n Hi Again"];
(2):
NSMutableString *a = [NSMutableString stringWithString:@"Hi"];
[a appendString:@"\n\n Hi Again"];
或(3):
NSString *a = [NSString stringWithFormat:@"%@%@", @"Hi", @"\n\n Hi again"];
(1)会给你两个字符串(一个是可变的,一个是不可变的),(2)会给你一个可变的字符串,(3)会给你一个不可变的字符串。
答案 4 :(得分:0)
如果您的字符串是在UIView中(例如UILabel),您还需要将行数设置为0
myView.numberOfLines=0;