从NSMutableArray中删除空值

3
我有一个数组,我想删除值为 @"" 或没有值的项。我希望保留具有值的数组并返回其新长度。 如何实现这一点?
array:{
"24_7" = 1;
"abo_ok" = "";
city = "";
"compte_ok" = "";
country = FR;
"credit_card" = "Mastercard, Visa";
"date_creation" = "2011-11-05 18:01:56";
"debut_abo" = "";
dst = "992.565700179622";
email = "";
"fin_abo" = "";
"h_saturday" = "";
"h_sunday" = "";
"h_week" = "";
handicapped = "Malades assis";
hours = "";
id = 614;
"id_driver" = 614;
"info_compl" = "";
languages = "";
"location_lat" = "48.6823";
"location_long" = "6.17818";
luggage = 0;
luxury = "";
name = "Taxi";
nbvotes = "";
passengers = 4;
query = 8;
score = 9;
"special_trip" = "A\U00e9roport, Colis";
status = 2;
"tel_1" = 0383376537;
"tel_2" = "";
vehicles = "";
votes = "";
}

看起来更像NSDictionary! - Ozair Kafray
是的,我也这么认为,但是无法删除空的。 - Tidane
在这种情况下,请将您的问题标题从NSMutableArray更改为NSMutableDictionary! - Ozair Kafray
此外,这个答案可以帮助你解决问题:https://dev59.com/YGox5IYBdhLWcg3wFAfW#9446317 - Ozair Kafray
5个回答

10
[myMutableArray removeObject: @""];

从数组中删除 @""所有实例。这里是-removeObject的文档

另外,如果评论中所暗示的那样,您确实拥有可变字典

NSArray* keysToGo = [myDictionary allKeysForObject: @""];
[myDictionary removeObjectsForKeys: keysToGo];

2
尝试这个。
NSMutableSet* set = [NSMutableSet setWithArray:array];
[set removeObject:@""];
NSArray *result =[set allObjects];
NSLog(@"%@",result);

0
你可以使用NSMutableArray的removeObjectIdenticalTo:方法,如下所示。
[yourMutArray removeObjectIdenticalTo:[NSNull null]];

去除空值。 无需迭代。


0

你可以遍历整个数组并检查每个值的长度。如果值的长度 <= 0,则从数组中删除该对象。


0

只需循环遍历数组并删除长度为0的每个字符串:

for(int idx = 0; idx < array.count; idx++) {
    if([[array objectAtIndex:idx] isKindOfClass:[NSString class]]) { //type check
        if(((NSString*)[array objectAtIndex:idx]).length == 0) { //test for string length

            //finally, pull out that string
            [array removeObjectAtIndex:idx]; 

            //because we removed an object, we have to decrement the 
            //counter to avoid skipping the next string
            idx--; 
        }
    }
}

你可以通过不使用点语法来摆脱丑陋的类型转换。[[array objectAtIndex:idx] length] - JeremyP
是的,我知道,但出于某种原因,我内心深处总有一部分需要始终使用点语法来访问属性,而另一部分则只需要使用Smalltalk消息语法来调用方法... 可以称之为强迫症... - eric.mitchell
哈!我的某部分总是需要使用消息语法,因为点语法应该在出生时就被淘汰了(部分原因就是这个)。 :-) - JeremyP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接