我想插入一堆對象到NSMutableArray中。然後,我會在適合的時候一個接一個地刪除它們。每個插入的對象都必須刪除。如何從nsmutablearray中刪除至多一個對象?
但是,如果我有同一個對象的多個副本,我只想刪除其中的一個。
我該怎麼做?
我想插入一堆對象到NSMutableArray中。然後,我會在適合的時候一個接一個地刪除它們。每個插入的對象都必須刪除。如何從nsmutablearray中刪除至多一個對象?
但是,如果我有同一個對象的多個副本,我只想刪除其中的一個。
我該怎麼做?
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
}
還要注意的是,如果對象避免你的數組充滿了自定義對象,你需要實現hash
和isEqual:
,以便比較可以工作。
是你正在尋找的任何這些功能?
[array removeObjectAtIndex:(NSUInteger)];
[array removeLastObject];
[array removeObject:(id)];
[myMutableArray removeObjectAtIndex: 0];
或
[myMutableArray removeLastObject];
要分別取出第一個和最後的對象。
我不認爲這是一個很好的設計[NSMutableArray removeObject:]
刪除所有的出現次數,但我們可以先用indexOfObject:
得到一個索引,然後取出用removeObjectAtIndex:
我更喜歡使用對象的索引;它會返回數組中第一個出現的對象索引
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:'刪除對象的所有實例。其他兩個是所期望的。 –
是的,我只是把它放在那裏好的措施 – Fonix