Objective C - 使用stringByAppendingFormat的多行字符串

时间:2013-09-11 06:20:21

标签: objective-c nsstring spacing

我遇到以下代码的问题。我希望结果multiLineTitle看起来像这样

Each
Word
Should 
Have 
Its 
Own 
Line

但是当我运行此程序时,multiLineTitle结束null。有谁能发现这个问题?

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

    }

2 个答案:

答案 0 :(得分:1)

将空字符串分配给multiLineTitle或为multiLineTitle分配内存。

NSString *multiLineTitle = @"";

NSString *multiLineTitle = [[NSString alloc]init];

答案 1 :(得分:0)

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