【问题标题】:how to check if there is any item which is to be added in array is empty如何检查是否有任何要添加到数组中的项目为空
【发布时间】:2012-08-28 11:23:28
【问题描述】:

如何检查是否在数组中添加了任何项字符串并且该项为空,那么如何在运行时将其从数组中删除 我有像

这样的数组
    NSArray *myArray = [[NSArray alloc] initWithObjects:iphone,droid,blackberry,donotUse,window,other,nil];

我希望如果 iphone 在运行时为空,它不应该在数组中。

因为如果它是空的,那么它不会显示其余的值,所以如何解决这个问题。

【问题讨论】:

  • simple , if(iPhone != nil ) {将其添加到数组中否则不}。
  • 如果是字符串则使用 stringByTrimmingCharactersInSet 方法检查是否为空。
  • stackoverflow.com/questions/7361650/…。它认为这是您问题的答案。

标签: iphone xcode nsarray


【解决方案1】:

改为使用NSMutableArray,并且仅在与nil不同时才添加:

NSMutableArray *arr = [[NSMutableArray alloc] init];
if([iphone length] > 0)
  [arr addObject:iphone];
...

【讨论】:

  • 他问如何检查它是否为空字符串。所以我认为使用了 stringByTrimmingCharInSet 方法。
【解决方案2】:
NSArray *myArray = [[NSArray alloc] initWithObjects:iphone,droid,blackberry,donotUse,window,other,nil];
NSMutableArray *cleanArray = [[NSMutableArray alloc] init];

for(int i = 0 ; i < [myArray count]; i++)
{
   if([[myArray objectAtIndex:i] length])
       [cleanArray addObject:[myArray objectAtIndex:i]];   
}

【讨论】:

    【解决方案3】:

    这样做:

    NSMutableArray *arrValues = [[NSMutableArray alloc]init];
    
    for(NSString *str in myArray)
    {
     if (str != (id)[NSNull null] || str.length != 0 )
     {
        [arrValues addObject:str]; 
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多