ios 从 NSMutableArray 中删除对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16015927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:11:34  来源:igfitidea点击:

Remove object from NSMutableArray?

iosobjective-csearchnsstringnsmutablearray

提问by Naveen

I have an array with following elements in ViewDidLoadmethod

我在ViewDidLoad方法中有一个包含以下元素的数组

inputArray = [NSMutableArray arrayWithObjects:@"car", @"bus", @"helicopter", @"cruiz", @"bike", @"jeep", nil];

I have another UITextFieldfor searching the elements .So once i type some thing in UITextFieldi want to check whether that string is present in "inputArray" or not.If it is not matching with elements in inputArray then remove the corresponding elements from inputArray .

我有另一个UITextField用于搜索元素。所以一旦我输入一些东西,UITextField我想检查该字符串是否存在于“inputArray”中。如果它与 inputArray 中的元素不匹配,则从 inputArray 中删除相应的元素。

 for (NSString* item in inputArray)
   {
        if ([item rangeOfString:s].location == NSNotFound) 
        {
            [inputArray removeObjectIdenticalTo:item];//--> Shows Exception
            NSLog(@"Contains :%@",containsAnother);
        }

  }

but this code shows exception , something related to "removeobject:"

但此代码显示异常,与“removeobject:”相关的内容

Exception :

例外 :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSCFConstantString rangeOfString:options:range:locale:]: nil argument'
*** First throw call stack:
`

回答by Anoop Vaidya

In fast enumeration you can NOTmodify the collection.

在快速枚举中,您不能修改集合。

The enumerator object becomes constant and immutable.

枚举器对象变为常量和不可变的。

If you want to do updation on the array

如果你想对阵列进行更新

You should like this :

你应该喜欢这个:

NSMutableArray *inputArray = [NSMutableArray arrayWithObjects:@"car", @"bus", @"helicopter", @"cruiz", @"bike", @"jeep", nil];
NSString *s=@"bus";

for (int i=inputArray.count-1; i>-1; i--) {
    NSString *item = [inputArray objectAtIndex:i];
    if ([item rangeOfString:s].location == NSNotFound) {
        [inputArray removeObject:item];
    }
}

EDIT:

编辑:

The above works similar as this :

上面的工作类似于这样:

NSArray *array=[inputArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",s]]; 

回答by Muhammad Nabeel Arif

You can use the following code

您可以使用以下代码

for (int i=0;i<[inputArray count]; i++) {
        NSString *item = [inputArray objectAtIndex:i];
        if ([item rangeOfString:s].location == NSNotFound) {
            [inputArray removeObject:item];
            i--;
        }
    }

回答by LJ Wilson

That needs to be an NSMutableArray. You can't modify an NSArrayonce created (except to start all over).

那需要是一个NSMutableArray. 您不能修改NSArray一次创建(除非重新开始)。

Change this:

改变这个:

inputArray = [NSArray arrayWithObjects:@"car", @"bus", @"helicopter", @"cruiz", @"bike", @"jeep", nil];

to this:

对此:

inputArray = [NSMutableArray arrayWithObjects:@"car", @"bus", @"helicopter", @"cruiz", @"bike", @"jeep", nil];

and also change the property to NSMutableArray also:

并将该属性也更改为 NSMutableArray:

@property(nonatomic, strong) NSMutableArray *inputArray;

回答by Vignesh

The sin your question is probably nil. So your are getting the exception.Please check that out.

s你的问题很可能是零。所以你得到了异常。请检查一下。

回答by Pedro Mancheno

This is a clean solution that I like to use. You define a NSArray category to extend it and create a mapmethod. This method creates a new NSArray based on what you return within your block:

这是我喜欢使用的干净解决方案。您定义一个 NSArray 类别来扩展它并创建一个map方法。此方法根据您在块中返回的内容创建一个新的 NSArray:

@interface NSArray (BlockExtensions)
/*! 
 Invokes block once for each element of self, returning a new array containing the
 values returned by the block.
 */
- (NSArray *)map:(id (^)(id obj))block;

@end

@implementation NSArray (BlockExtensions)

- (NSArray *)map:(id (^)(id obj))block
{
    return [self mapWithOptions:0 usingBlock:^id(id obj, NSUInteger idx) {
        return block(obj);
    }];
} 

- (NSArray *)mapWithOptions:(NSEnumerationOptions)options usingBlock:(id (^)(id obj, NSUInteger idx))block
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];
    [self enumerateObjectsWithOptions:options usingBlock:^(id obj, NSUInteger idx, BOOL *stop)     {

        id newobj = block? block(obj, idx) : obj;
        if (newobj)
            [array addObject:newobj];
    }];
    return array;
}
    @end

The block will be called once for every item in your original array, passing this object as a parameter:

该块将为原始数组中的每个项目调用一次,将此对象作为参数传递:

NSArray *newArray = [inputArray map:^id(NSString *item) {
    if ([item rangeOfString:s].location == NSNotFound) {
        return item;
    }
    return nil;
}];

newArraywill contain your filtered out items!

newArray将包含您过滤掉的项目!

回答by iPatel

Use following Code. (This Code is use for filter Array base on input string/text of UITextField)

使用以下代码。(此代码用于基于输入字符串/文本的过滤器数组UITextField

Take Two NSMutableArrayand add one array to another arrayin ViewDidLoadmethod such like,

采取两个NSMutableArray一个阵列添加到另一个阵列ViewDidLoad的方法例如等

self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:@"YorArrayList", nil]; // array no - 2 

[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array

And Write following delegate Method of UISearchBar

并编写以下 UISearchBar 的委托方法

- (BOOL) textFieldDidChange:(UITextField *)textField
 {
        NSString *name = @"";
        NSString *firstLetter = @"";

    if (self.listOfTemArray.count > 0)
         [self.listOfTemArray removeAllObjects];

        if ([searchText length] > 0)
        {
                for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
                {
                        name = [self.ItemOfMainArray objectAtIndex:i];

                        if (name.length >= searchText.length)
                        {
                                firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
                                //NSLog(@"%@",firstLetter);

                                if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
                                {
                                    // strings are equal except for possibly case
                                    [self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
                                    NSLog(@"=========> %@",self.listOfTemArray);
                                }
                         }
                 }
         }
         else
         {
             [self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
         }

        [self.tblView reloadData];
}

}

}

Output Show in your Console.

输出显示在您的 Console.

回答by James P

As others have said you can't mutate an array while it is being enumerated. The easiest way to do what you want and keep the convenience of fast enumeration is to copy the array.

正如其他人所说,您不能在枚举数组时对其进行变异。做你想做的并保持快速枚举的便利的最简单方法是复制数组。

for (NSString* item in [inputArray copy]) {
   ...
}

回答by Rob

+1 to Anoop for pointing out that you can use filteredArrayUsingPredicate. Thus, if you wanted to create a new array based upon the matches in inputArray, you could also use something like:

+1 Anoop 指出您可以使用filteredArrayUsingPredicate. 因此,如果您想根据 中的匹配项创建一个新数组inputArray,您还可以使用以下内容:

NSArray *matchingArray = [inputArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[c] %@", s]];

Alternatively, given that inputArrayis a NSMutableArrayyou can simply filter the array with this single line:

或者,鉴于这inputArray是一个,NSMutableArray您可以使用这一行简单地过滤数组:

[inputArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[c] %@", s]];

Or, if you like blocks:

或者,如果您喜欢块:

[inputArray filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    return ([evaluatedObject rangeOfString:s].location != NSNotFound);
}]];