Files
real-e-party-iOS/YuMi/Tools/Safe/NSMutableArray+Safe.m
2025-10-17 14:52:29 +08:00

67 lines
1.8 KiB
Objective-C

// Created by YUMI on 2023/11/15.
#import "NSMutableArray+Safe.h"
@implementation NSMutableArray (Safe)
- (void)xpSafeRemoveObjectAtIndex:(NSUInteger)index {
if ([self isKindOfClass:[NSMutableArray class]]) {
if (self.count > 0 && index < self.count) {
[self removeObjectAtIndex:index];
}
}
}
- (void)xpSafeRemoveObject:(id)anObject {
if ([self isKindOfClass:[NSMutableArray class]]) {
if (anObject && [self containsObject:anObject]) {
[self removeObject:anObject];
}
}
}
- (void)xpSafeRemoveObjectsAtIndexes:(NSIndexSet *)indexes {
if ([self isKindOfClass:[NSMutableArray class]] && indexes) {
NSMutableIndexSet *validIndexes = [NSMutableIndexSet indexSet];
[indexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
if (idx < self.count) {
[validIndexes addIndex:idx];
}
}];
if (validIndexes.count > 0) {
[self removeObjectsAtIndexes:validIndexes];
}
}
}
- (void)xpSafeInsertObject:(id)anObject atIndex:(NSUInteger)index {
if ([self isKindOfClass:[NSMutableArray class]] && anObject) {
if (index <= self.count) {
[self insertObject:anObject atIndex:index];
} else if (index > self.count) {
[self addObject:anObject];
}
}
}
- (void)xpSafeReplaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject {
if ([self isKindOfClass:[NSMutableArray class]] && anObject) {
if (index < self.count) {
[self replaceObjectAtIndex:index withObject:anObject];
}
}
}
- (void)xpSafeRemoveAllObjects {
if ([self isKindOfClass:[NSMutableArray class]] && self.count > 0) {
[self removeAllObjects];
}
}
@end