与“,”分开?

时间:2012-04-23 14:32:39

标签: ios xcode

我通过这样的数组迭代。

NSArray *array = [[currentRaum raumattribute] allObjects];

    NSString *compositeString = [ [ NSString alloc ] init ];
    for( Raumattribute *attr in array ){
        compositeString = [ NSString stringWithFormat:@"%@ %@",compositeString, attr.attributname ];
    [raumAttributLabel setText:compositeString];

我想要一个类似的输出---->猫,狗,小鼠

但如果我这样做:

compositeString = [ NSString stringWithFormat:@"%@ %@,",compositeString, attr.attributname ];

输出是Cat,Dog,Mouse,

或者如果我这样做:

compositeString = [ NSString stringWithFormat:@"%@ ,%@",compositeString, attr.attributname ];

输出它,猫,狗,鼠标

有解决方案吗?

1 个答案:

答案 0 :(得分:4)

您可以使用数组的valueForKey:componentsJoinedByString:方法来实现这一目标:

NSString * compositeString =  [[array valueForKey:@"attributname"] componentsJoinedByString:@","]

valueForKey:将为每个数组元素

创建一个attributname值数组

componentsJoinedByString:会将这些值合并为一个以逗号分隔的字符串