-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSObject+Safety.m
More file actions
78 lines (61 loc) · 1.82 KB
/
NSObject+Safety.m
File metadata and controls
78 lines (61 loc) · 1.82 KB
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
//
// NSObject+Safety.m
// 加法计算器
//
// Created by Hock on 2020/5/9.
// Copyright © 2020 Hock. All rights reserved.
//
#import "NSObject+Safety.h"
#import <objc/runtime.h>
static NSString *objKey = @"obj";
@implementation NSObject (Safety)
- (void)setObj:(id)obj {
objc_setAssociatedObject(self, &objKey, obj, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (id)obj {
id value = objc_getAssociatedObject(self, &valueKey);
self.value = nil;
return value;
}
- (NSObject * _Nullable (^)(NSString * _Nullable))objForKey {
return ^NSObject * _Nullable (NSString *key) {
if (!key || !key.length) {
return [NSObject new];
}
NSDictionary *dict = (NSDictionary *)self.obj;
if (!dict) {
dict = (NSDictionary *)self;
}
if ([dict isKindOfClass:[NSDictionary class]]) {
if ([[dict objectForKey:key] isKindOfClass:[NSNull class]]) {
return [NSObject new];
}
self.obj = [dict objectForKey:key];
return self;
}
return [NSObject new];
};
}
- (NSObject * _Nullable (^)(NSInteger))objAtIndex {
return ^NSObject * _Nullable (NSInteger index) {
if (index < 0) {
return [NSObject new];
}
NSArray *array = (NSArray *)self.obj;
if (!array) {
array = (NSArray *)self;
}
if ([array isKindOfClass:[NSArray class]]) {
if (array.count < index + 1) {
return [NSObject new];
}
if ([[array objectAtIndex:index] isKindOfClass:[NSNull class]]) {
return [NSObject new];
}
self.obj = [array objectAtIndex:index];
return self;
}
return [NSObject new];
};
}
@end