iOS 防止数组越界 对象类型不一致的安全处理 使用category对nsmutablearray处理

#import "NSMutableArray+FKAdd.h"


@implementation NSMutableArray (FKAdd)


- (void)fk_addObject:(id)anObject {

    if (!anObject) {

        NSAssert(anObject, @"warning: 请不要添加空数据!");

        return;

    }

    if (self == anObject) {

        NSAssert(anObject != self, @"warning: 请不要添加自身!");

        return;

    }

    [self addObject:anObject];

}


- (void)fk_insertObject:(id)anObject atIndex:(NSUInteger)index {

    if (index < 0) {

        NSAssert(index >= 0, @"warning: 插入的下标为负!");

        return;

    }

    if (index > self.count) {

        NSAssert(index <= self.count, @"warning: 插入的下标越界!");

        return;

    }

    if (!anObject) {

        NSAssert(anObject, @"warning: 请不要添加空数据!");

        return;

    }

    if (self == anObject) {

        NSAssert(anObject != self, @"warning: 请不要插入自身!");

        return;

    }

    [self insertObject:anObject atIndex:index];

}


- (void)fk_removeObjectAtIndex:(NSUInteger)index {

    if (index < 0) {

        NSAssert(index >= 0, @"warning: 移除的下标为负!");

        return;

    }

    if (index >= self.count) {

        NSAssert(index < self.count, @"warning: 移除的下标越界!");

        return;

    }

    [self removeObjectAtIndex:index];

}


- (void)fk_replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject {

    if (index < 0) {

        NSAssert(index >= 0, @"warning: 替换的下标为负!");

        return;

    }

    if (index >= self.count) {

        NSAssert(index < self.count, @"warning: 替换的下标越界!");

        return;

    }

    if (!anObject) {

        NSAssert(anObject, @"warning: 请不要用空数据替换!");

        return;

    }

    if (self == anObject) {

        NSAssert(self != anObject, @"warning: 请不要用自身进行替换!");

        return;

    }

    [self replaceObjectAtIndex:index withObject:anObject];

}




- (NSMutableArray*(^)(id))fk_addObject {

    return ^NSMutableArray*(id anObject) {

        if (!anObject) {

            NSAssert(anObject, @"warning: 请不要添加空数据!");

            return self;

        }

        if (self == anObject) {

            NSAssert(self != anObject, @"warning: 请不要添加自身!");

            return self;

        }

        [self addObject:anObject];

        return self;

    };

}


- (NSMutableArray*(^)(NSUInteger))fk_removeObjectAtIndex {

    return ^NSMutableArray*(NSUInteger index) {

        if (index < 0) {

            NSAssert(index >= 0, @"warning: 移除的下标为负!");

            return self;

        }

        if (index >= self.count) {

            NSAssert(index < self.count, @"warning: 移除的下标越界!");

            return self;

        }

        [self removeObjectAtIndex:index];

        return self;

    };

}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值