我像这样遍历一个数组。

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


输出其,Cat,Dog,Mouse

有解决方案吗?

最佳答案

您可以使用数组的valueForKey:componentsJoinedByString:方法做到这一点:

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


valueForKey:将为每个数组元素创建属性名称值数组

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

关于ios - 以“,”分隔吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10282597/

10-12 14:59