1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//
// NSMutableArray+SafeInsert.m
// XFFruit
//
// Created by Xummer on 4/10/15.
// Copyright (c) 2015 Xummer. All rights reserved.
//
#import "NSMutableArray+SafeInsert.h"
#pragma mark - NSMutableArray (SafeInsert)
@implementation NSMutableArray (SafeInsert)
- (void)safeAddObject:(id)object {
if (object) {
[self addObject:object];
}
}
- (void)safeInsertObject:(id)object atIndex:(NSUInteger)index {
if (index < self.count && object) {
[self insertObject:object atIndex:index];
}
}
- (void)safeRemoveObjectAtIndex:(NSUInteger)index {
if (index < self.count) {
[self removeObjectAtIndex:index];
}
}
- (void)safeReplaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
if (index < self.count && object) {
[self replaceObjectAtIndex:index withObject:object];
}
}
- (void)removeFirstObject {
id firstObj = [self firstObject];
if (firstObj) {
[self removeObject:firstObj];
}
}
@end
#pragma mark - NSMutableDictionary (SafeInsert)
@implementation NSMutableDictionary (SafeInsert)
- (void)safeSetObject:(id)object forKey:(id <NSCopying>)key {
if (object) {
[self setObject:object forKey:key];
}
}
- (void)safeRemoveObjectForKey:(id)key {
[self removeObjectForKey:key];
}
@end
#pragma mark - NSMutableSet (SafeInsert)
@implementation NSMutableSet (SafeInsert)
- (void)safeAddObject:(id)object {
if (object) {
[self addObject:object];
}
}
- (void)safeRemoveObject:(id)object {
if (object) {
[self removeObject:object];
}
}
@end
#pragma mark - NSMutableString (SafeInsert)
@implementation NSMutableString (SafeInsert)
- (void)safeAppendString:(NSString *)string {
if ([string isKindOfClass:[NSString class]]) {
[self appendString:string];
}
}
@end
#pragma mark - NSArray (SafeFetch)
@implementation NSArray (SafeFetch)
- (id)safeObjectAtIndex:(NSUInteger)index {
@synchronized(self) {
if (index >= [self count]) return nil;
return [self objectAtIndex:index];
}
}
@end