NSString from NSArray

妖精的绣舞 提交于 2019-12-05 09:03:06
Alladinian

Another way to do this is to grab a mutable copy of the array and just remove non valid objects. Something like this perhaps:

NSMutableArray *array = [[NSArray arrayWithObjects:@"",@"World",nil] mutableCopy];
[array removeObject:@""]; // Remove empty strings
[array removeObject:[NSNull null]]; // Or nulls maybe

NSLog(@"%@", [array componentsJoinedByString:@","]);

You cannot store nil values in NSArray*, so the answer is "no". You need to iterate the array yourself, keeping track of whether you need to add a comma or not.

NSMutableString *res = [NSMutableString string];
BOOL first = YES;
for(id item in array) {
    if (id == [NSNull null]) continue;
    // You can optionally check for item to be an empty string here
    if (!first) {
        [res appendString:@", "];
    } else {
        first = NO;
    }
    [res appendFormat:@"%@", item];
}


*nil values in NS collections are represented with NSNull objects.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!