NSString: newline escape in plist

前端 未结 5 603
终归单人心
终归单人心 2020-12-04 21:23

I\'m writing a property list to be in the resources bundle of my application. An NSString object in the plist needs to have line-breaks in it. I tried \\n

相关标签:
5条回答
  • 2020-12-04 21:41

    a little late, but i discovered the same issue and i also discovered a fix or workaround. so for anyone who stumbles on this will get an answer :)

    so the problem is when you read a string from a file, \n will be 2 characters unlike in xcode the compiler will recognize \n as one.

    so i extended the NSString class like this:

    "NSString+newLineToString.h":

    @interface NSString(newLineToString)    
    -(NSString*)newLineToString;   
    @end
    

    "NSString+newLineToString.m":

    #import "NSString+newLineToString.h"
    
    @implementation NSString(newLineToString)
    
    -(NSString*)newLineToString
    {
        NSString *string = @"";
        NSArray *chunks = [self componentsSeparatedByString: @"\\n"];
    
        for(id str in chunks){
            if([string isEqualToString:@""]){
                string = [NSString stringWithFormat:@"%@",str];
            }else{
                string = [NSString stringWithFormat:@"%@\n%@",string,str];
            }
    
        }
        return string;
    } 
    @end
    

    How to use it:

    rootDict = [[NSDictionary alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"yourFile" ofType:@"plist"]];
    
    NSString *string = [[rootDict objectForKey:@"myString"] newLineToString];
    

    its quick and dirty, be aware that \\n in your file will not be recognize as \n so if you need to write \n on text you have to modify the method :)

    0 讨论(0)
  • 2020-12-04 21:49

    If you're editing the plist in Xcode's inbuild plist editor, you can press option-return to enter a line break within a string value.

    0 讨论(0)
  • 2020-12-04 22:03

    I found a simpler solution:

    NSString *newString = [oldString stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
    

    It seems the string reader escapes all characters that need to be escaped such that the text from the plist is rendered verbatim. This code effectively drops the extra escape.

    0 讨论(0)
  • 2020-12-04 22:04

    Edit your plist using a text editor instead of Xcode's plist editor. Then you simply put line breaks in your strings directly:

    <string>foo
    bar</string>
    
    0 讨论(0)
  • 2020-12-04 22:08

    This is how I do loading my plist in Swift 2.0:

    plist:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>STRING_TEXT</key>
        <string>This string contains an emoji and a double underscore                                                                    
    0 讨论(0)
提交回复
热议问题