简体   繁体   English

目标C-使用stringByAppendingFormat的多行字符串

[英]Objective C - Multi line string using stringByAppendingFormat

I'm having an issue with the following code. 我的以下代码有问题。 I want the resultant multiLineTitle to look like this 我希望生成的multiLineTitle看起来像这样

Each
Word
Should 
Have 
Its 
Own 
Line

But when I run this program, multiLineTitle ends up null . 但是,当我运行该程序时, multiLineTitle最终为null Can anyone spot the issue? 谁能发现这个问题?

    NSString *title = "Each Word Should Have Its Own Line";
    NSString *multiLineTitle;

    NSArray *words = [title componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];

    for (int len = 0; len < [words count]; len++){
        multiLineTitle = [multiLineTitle stringByAppendingFormat:@"%@ \n", words[len]];

    }

assign empty string to multiLineTitle or allocate memory for multiLineTitle. 将空字符串分配给multiLineTitle或为multiLineTitle分配内存。

NSString *multiLineTitle = @"";

or 要么

NSString *multiLineTitle = [[NSString alloc]init];
solution....
NSString *title =@"Each Word Should Have Its Own Line";
    NSMutableString *multiLineTitle =[[NSMutableString alloc] init];

    NSArray *words = [title componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];

    for (int len = 0; len < [words count]; len++){
     [multiLineTitle appendFormat:@"%@\n",[words objectAtIndex:len]];

    }
    NSLog(@"multiLineTitle:%@",multiLineTitle);




ans:
multiLineTitle:Each
Word
Should
Have
Its
Own
Line

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM