NSMutableArray中removeObjectAtIndex和removeObject的正確使用方法

小萌在做開(kāi)發(fā)拖拽單元格移動(dòng)的時(shí)候遇到的坑,這是一個(gè)小萌忽略的問(wèn)題。removeObjectAtIndex和removeObject的兩者雖然都是刪除,可是卻有很大的不同

1、removeObject刪除對(duì)象

api上是這么解釋的。
Removes all occurrences in the array of a given object.
This method uses indexOfObject: to locate matches and then removes them by using removeObjectAtIndex:. Thus, matches are determined on the basis of an object’s response to the isEqual: message. If the array does not contain anObject, the method has no effect (although it does incur the overhead of searching the contents).

刪除NSMutableArray中所有isEqual:待刪對(duì)象的對(duì)象

也就是說(shuō)removeObject:可以刪除多個(gè)對(duì)象(只要符合isEqual:的都刪除掉,只要兩個(gè)對(duì)象相等都可以刪除掉)。

2、removeObjectAtIndex

api上這樣解釋的。

Removes the object at index .
To fill the gap, all elements beyond index are moved by subtracting 1 from their index.

Important:Important
Raises an exception NSRangeException if index is beyond the end of the array.

刪除指定NSMutableArray中指定index的對(duì)象,注意index不能越界,只能刪除一個(gè)元素。

3、舉例說(shuō)明

tempArray 臨時(shí)數(shù)組
[@"how", @"to", @"remove", @"remove", @"object",@"remove", @"true"]

就拿上面的數(shù)組舉例吧

(一)removeObject刪除

[tempArray removeObject:@"remove"];

輸出結(jié)果:

//所有@"remove"都被刪掉
[@"how", @"to", @"object", @"true"]

(二)removeObjectAtIndex刪除

[tempArray removeObjectAtIndex:2];

輸出結(jié)果:

只刪掉一個(gè)下標(biāo)為2的@"remove"元素,其他的都還在
[@"how", @"to", @"remove", @"object",@"remove", @"true"]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容