Objective c 如何从nsmutablearray中最多删除一个对象?
我想在NSMutableArray中插入一组对象。到时候我会把它们一个一个地拿走。必须删除每个插入的对象 但是,如果我有同一对象的多个副本,我只想删除其中一个Objective c 如何从nsmutablearray中最多删除一个对象?,objective-c,nsmutablearray,Objective C,Nsmutablearray,我想在NSMutableArray中插入一组对象。到时候我会把它们一个一个地拿走。必须删除每个插入的对象 但是,如果我有同一对象的多个副本,我只想删除其中一个 我该怎么做呢?这些函数中有你想要的吗 [array removeObjectAtIndex:(NSUInteger)]; [array removeLastObject]; [array removeObject:(id)]; 您是否正在寻找这些函数中的任何一个 [array removeObjectAtIndex:(NSUIntege
我该怎么做呢?这些函数中有你想要的吗
[array removeObjectAtIndex:(NSUInteger)];
[array removeLastObject];
[array removeObject:(id)];
您是否正在寻找这些函数中的任何一个
[array removeObjectAtIndex:(NSUInteger)];
[array removeLastObject];
[array removeObject:(id)];
或
分别删除第一个和最后一个对象
或
分别删除第一个和最后一个对象。我认为对于
[NSMutableArray removeObject:]
删除所有发生的事件,但我们可以通过先使用索引对象获取索引,然后使用删除对象索引:
来避免它,我认为这不是[NSMutableArray removeObject:]的好设计
删除所有发生的事件,但我们可以通过首先使用indexOfObject:
获取索引,然后使用removeObjectAtIndex:
NSMutableArray *arr = [@[@1, @1, @5, @6, @5] mutableCopy]; // a copy of your array
NSMutableSet *removedObjects = [NSMutableSet setWithArray:arr];
for (id obj in removedObjects) {
[arr removeObjectAtIndex:[arr indexOfObject:obj]]; // removes the first identical object
}
还请注意,如果数组中填充了自定义对象,则需要实现哈希
和isEqual:
,以便进行比较
还请注意,如果数组中填充了自定义对象,则需要实现散列
和isEqual:
,以便进行比较。我更喜欢使用对象索引;它将返回数组中首次出现的对象的索引
NSMutableArray * first = [@[@"2",@"3",@"4",@"5"] mutableCopy];//your first array
NSMutableArray * willBeAppend = [@[@"2",@"3",@"4",@"5"] mutableCopy];//new objects to append
[first addObjectsFromArray:willBeAppend];//append new objects
id objectToBeRemoved = @"3";// object will be removed
NSInteger objIx = [first indexOfObject:objectToBeRemoved];// index of object
if (objIx != NSNotFound) {
[first removeObjectAtIndex:objIx]; //remove object
NSLog(@"%@",first);
}
我更喜欢使用对象索引;它将返回数组中首次出现的对象的索引
NSMutableArray * first = [@[@"2",@"3",@"4",@"5"] mutableCopy];//your first array
NSMutableArray * willBeAppend = [@[@"2",@"3",@"4",@"5"] mutableCopy];//new objects to append
[first addObjectsFromArray:willBeAppend];//append new objects
id objectToBeRemoved = @"3";// object will be removed
NSInteger objIx = [first indexOfObject:objectToBeRemoved];// index of object
if (objIx != NSNotFound) {
[first removeObjectAtIndex:objIx]; //remove object
NSLog(@"%@",first);
}
removeObject:
删除对象的所有实例。另外两个是所需的。removeObject:
删除对象的所有实例。另外两个是所需要的。