NSMutableArray數(shù)組越界崩潰解決
對一個可變數(shù)組操作很頻繁傅事,并且在多個線程操作同一個可變數(shù)組時匀奏,發(fā)生數(shù)組越界等崩潰是很常見的。所以使用runtime swizzle 塑陵,對其方法進行交換哎迄。然后在交換方法中對增,刪,改,查等做保護機制就可以避免數(shù)組越界造成的崩潰。
1.新建一個NSMutableArray的分類
#import
NS_ASSUME_NONNULL_BEGIN
@interfaceNSMutableArray (SafeMutableArray)
@end
NS_ASSUME_NONNULL_END
2.文件實現(xiàn)
需要導入runtime.h文件
#import<objc/runtime.h>
然后在load方法中聲明進行方法交換聲明
+ (void)load
{
? ? staticdispatch_once_tonceToken;
? ? dispatch_once(&onceToken, ^{
? ? ? ? idobj = [[selfalloc]init];
? ? ? ? [objswizzleInstanceMethod:@selector(addObject:)withMethod:@selector(m_addObject:)];
? ? ? ? [objswizzleInstanceMethod:@selector(objectAtIndex:)withMethod:@selector(m_objectAtIndex:)];
? ? });
}
交換方法的實現(xiàn)
- (void)swizzleInstanceMethod:(SEL)origSelector withMethod:(SEL)newSelector {
? ? Classcls = [selfclass];
? ? MethodoriginalMethod =class_getInstanceMethod(cls, origSelector);
? ? MethodswizzledMethod =class_getInstanceMethod(cls, newSelector);
? ? BOOLdidAddMethod =class_addMethod(cls,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? origSelector,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? method_getImplementation(swizzledMethod),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? method_getTypeEncoding(swizzledMethod));
? ? if(didAddMethod) {
? ? ? ? class_replaceMethod(cls,
? ? ? ? ? ? ? ? ? ? ? ? ? ? newSelector,
? ? ? ? ? ? ? ? ? ? ? ? ? ? method_getImplementation(originalMethod),
? ? ? ? ? ? ? ? ? ? ? ? ? ? method_getTypeEncoding(originalMethod));
? ? }else{
? ? ? ? method_exchangeImplementations(originalMethod, swizzledMethod);
? ? }
}
- (void)m_addObject:(id)anObject
{
? ? if(nil!= anObject) {
? ? ? ? [selfm_addObject:anObject];
? ? }
? ? else
? ? {
? ? ? ? NSLog(@"這雖然是空數(shù)據(jù)斤蔓,但是不會crash");
? ? }
}
- (id)m_objectAtIndex:(NSUInteger)index
{
? ? if(index
? ? ? ? return[selfm_objectAtIndex:index];
? ? }
? ? else
? ? {
? ? ? ? NSLog(@"雖然數(shù)組越界植酥,但是不會crash");
? ? ? ? returnnil;
? ? }
}