天天看點

iOS開發中常見的一些異常

iOS開發中常見的異常包括以下幾種

NSInvalidArgumentException

NSRangeException

NSGenericException

NSInternallnconsistencyException

NSFileHandleOperationException

NSInvalidArgumentException

非法參數異常是objective-C代碼最常出現的錯誤,是以平時寫代碼的時候,需要多加注意,加強對參數的檢查,避免傳入非法參數導緻異常,其中尤以nil參數為甚。

1、集合資料的參數傳遞

比如NSMutableArray,NSMutableDictionary的資料操作

(1)NSDictionary不能删除nil的key

NSInvalidArgumentException reason, -[__NSCFDictionary removeObjectForKey:]:attempt to remove nil key

(2)NSDictionary不能添加nil的對象

NSInvalidArgumentException reason,***-[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[4]

(3)不能插入nil的對象

NSInvalidArgumentException reason,***-[__NSArrayM insertObject:atIndex:]: object cannot be nil

(4)其他一些nil參數

NSInvalidArgumentException reason, -[__NSCFString hasSuffix:]: nil argument

2、其他一些API的使用

APP一般都會有網絡操作,免不了使用網絡相關接口,比如NSURL的初始化,不能傳入nil的http位址:NSInvalidArgumentException reason,***-[NSURL initFileURLWithPath:]: nil string parameter

3、為實作的方法

(1).h檔案裡函數名,卻忘了修改.m檔案裡對應的函數名

(2)使用第三方庫時,沒有添加”-ObjC”flag

(3)MRC時,大部分情況下是因為對象被提前release了,在我們心裡不希望他release的情況下,指針還在,對象已經不在了。

NSInvalidArgumentException reason =-[UIKBBlurredKeyView candidateList]: unrecognized selector sent to …

NSInvalidArgumentException reason =-[UIThreadSafeNode_responderForEditing]: unrecognized selector sent …

NSRangeException

越界異常(NSRangeException)也是比較常出現的異常,有如下幾種類型:

1、數組最大下标處理錯誤

比如數組長度count,index的下标範圍[0,count-1],在開發時,可能index的最大值超過數組的範文;

NSRangeException reason = ***-[_NSarrayM objectAtIndex:]: index 19 beyond bounds [0..15]

2、下标的值是其他變量指派

這樣會有很大的不确定性,可能是一個很大的整數值

NSRangeException reason = ***-[_NSarrayM objectAtIndex:]: index 2147483647 beyond bounds [0..4]

NSRangeException reason = ***-[_NSarrayM objectAtIndex:]: index 18446744073709551615 beyond bounds [0..4]

3、使用空數組

如果一個數組剛剛初始化還是空的,就對它進行相關操作

NSRangeException reason = ***-[_NSarrayM objectAtIndex:]: index 0 beyond bounds for empty array

是以,為了避免NSRangeException的發生,必須對傳入的index參數進行合法性檢查,是否在集合資料的個數範圍内。

NSGenericException

NSGenericException這個異常最容易出現在foreach操作中,在for in循環中如果修改所周遊的數組,無論你是add或remove,都會出錯,比如:

for (id elem in arr) {
    [arr removeObject:elem];
    }
           

執行上面的代碼會出現以下錯誤:

NSGenericException reason = *** Collection<__NSArrayM:0x175058330>was mutated whild being enumerated.

原因就在這 “for in”,它的内部周遊使用了類似 Iterator進行疊代周遊,一旦元素變動,之前的元素全部被失效,是以在foreach的循環當中,最好不要去進行元素的修改動作,若需要修改,循環改為for周遊,由于内部機制不同,不會産生修改後結果失效的問題。

for (NSINteger i=; i<[arr count]; i++) {
    id elem = [arr objectAtIndex:i];
    [arr removeObject:elem];
    }
           

NSMallocException

這也是記憶體不足的問題,無法配置設定足夠的記憶體空間

NSMallocException reason = ***-[NSConcreteMutableData appendBytes:length:]: unable to allocate memory for length(81310)

NSFileHandleOperationException

處理檔案時的一些異常,最常見的還是存儲空間不足的問題,比如應用頻繁的儲存文檔,緩存資料或者處理比較大的資料:

NSFileHandleOperationException reason:***-[NSConcreteFileHandle writeData:]: No space left on device

是以在檔案處理裡,需要考慮到手機存儲空間的問題。