单例模式下使用代理,野指针的判断

2017-10-24  本文已影响14人  彼诸

1.声明成员变量

@interface SpeechRecognizerManager()<SFSpeechRecognitionTaskDelegate>
{
    //要通知的对象集合
    id  ayDelegate[100];
}
/** 要通知调度的对象个数 */
@property (nonatomic, assign) NSUInteger nDelCount;
@end

2.添加调度对象

- (void)addObject:(id<ZTSpeechRecognizerDelegate>)obj {
    int i = [self delegateContainObj:obj];
    if (i < 0) {
        _nDelCount ++;
        ayDelegate[_nDelCount - 1] = obj;
        NSLog(@"speechRecognizerManager add obj success:%@",obj);

3.移出调度对象

- (void)removeObject:(id<ZTSpeechRecognizerDelegate>)obj {
    int i = [self delegateContainObj:obj];
    if (i >= 0) {
        [self delegateRemoveIndex:i];
        NSLog(@"speechRecognizerManager remove obj success:%@",obj);
    }
}
/**
 删除指定index的代理

 @param index 1
 */
- (void)delegateRemoveIndex:(NSUInteger)index {
    //容错处理
    if (index >= _nDelCount) return;
    //自index开始前移
    for (NSInteger i = index; i < _nDelCount; i ++) {
        if (i == _nDelCount) ayDelegate[i] = 0;
        else ayDelegate[i] = ayDelegate[i+1];
    }
    _nDelCount--;
}

4.判断调度对象是否已经存在

/**
 代理数组是否包含obj

 @param obj 1
 @return 若包含,返回所在index;不包含,返回-1
 */
- (int)delegateContainObj:(id<ZTSpeechRecognizerDelegate>)obj{
    BOOL bFind = NO;
    int index = -1;
    NSMutableArray *ayWildPoin =[[NSMutableArray alloc] init];
    for (int i = 0; i < _nDelCount; i ++) {
        id delegate = ayDelegate[i];
        //指针是否是有效指针
        if (malloc_zone_from_ptr((void *)delegate))
        {
            bFind = [delegate isEqual:obj];
            
        }
        else
        {
            //野指针
            [ayWildPoin addObject:@(i)];
        }
        if (bFind){
            index = i;
            break;
        }
    }
    //移出野指针
    for (int i = 0;i < ayWildPoin.count;i ++) {
        [self delegateRemoveIndex:[ayWildPoin[i] integerValue]];
    }
    index = index - (int)ayWildPoin.count;
    [ayWildPoin release];
    NSLog(@"delegate array contain:%zi",index);
    return index;
}
    }
}
上一篇下一篇

猜你喜欢

热点阅读