-
Notifications
You must be signed in to change notification settings - Fork 1
/
YSCMacros.h
375 lines (344 loc) · 13.9 KB
/
YSCMacros.h
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
//
// YSCMacros.h
// YSCKit
//
// Created by Builder on 16/6/29.
// Copyright © 2016年 Builder. All rights reserved.
//
#import <sys/time.h>
//==============================================================================
//
// @Description:
// 该文件定义了基础库YSCKit中常用的宏定义
//
//==============================================================================
#ifndef YSCMacros_h
#define YSCMacros_h
/** 处于调试或者开发模式 */
#define IS_DEBUG_OR_DEVELOP_MODE (YSCConfigManagerInstance.isDebugModel || [YSCGeneral isArchiveByDevelopment])
/** 是否输出log */
#define IS_NSLOG_AVAILABLE IS_DEBUG_OR_DEVELOP_MODE
#define __NSLog(s, ...) do { \
if (IS_NSLOG_AVAILABLE) { \
NSMutableString *logString = [NSMutableString stringWithFormat:@"[%@(%d)] ",[[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__]; \
if (s) { \
[logString appendFormat:(s), ##__VA_ARGS__]; \
} \
else { \
[logString appendString:@"(null)"]; \
} \
NSLog(@"%@", logString); \
[YSCLog saveLog:logString]; \
} \
} while (0)
#define NSLog(...) __NSLog(__VA_ARGS__)
/** 去掉字符串的头尾空格 */
#define TRIM_STRING(_string) (\
( ! [_string isKindOfClass:[NSString class]]) ? \
@"" : [_string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] \
)
/**
* 对象判空
* 注意:只对原始数据进行判断,即全空的字符串不为空
*/
#define OBJECT_IS_EMPTY(_object) (_object == nil \
|| [_object isKindOfClass:[NSNull class]] \
|| ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) \
|| ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] == 0))
#define OBJECT_ISNOT_EMPTY(_object) ( ! OBJECT_IS_EMPTY(_object))
#define RETURN_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return ; }
#define RETURN_NIL_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return nil; }
#define RETURN_EMPTY_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return @""; }
#define RETURN_YES_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return YES; }
#define RETURN_NO_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return NO; }
#define RETURN_ZERO_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return 0; }
/**
* 创建单例
*/
#ifndef DEFINE_SHARED_INSTANCE_USING_BLOCK
#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \
static dispatch_once_t pred = 0; \
__strong static id _sharedObject = nil; \
dispatch_once(&pred, ^{ \
if (block) { \
_sharedObject = block(); \
} \
}); \
return _sharedObject;
#endif
/**
* @brief swizzling instance method
*
* @usage:
* SWIZZLING_INSTANCE_METHOD(self.class, @selector(viewDidLoad), @selector(ysc_viewDidLoad))
*/
#ifndef SWIZZLING_INSTANCE_METHOD
#define SWIZZLING_INSTANCE_METHOD(clazz, originalSelector, swizzledSelector) { \
Method originalMethod = class_getInstanceMethod(clazz, originalSelector); \
Method swizzledMethod = class_getInstanceMethod(clazz, swizzledSelector); \
BOOL isAddedMethod = class_addMethod(clazz, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); \
if (isAddedMethod) { \
class_replaceMethod(clazz, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); \
} \
else { \
method_exchangeImplementations(originalMethod, swizzledMethod); \
} }
#endif
/**
* @brief swizzling class method
*
* @usage:
* SWIZZLING_INSTANCE_METHOD(object_getClass((id)self), @selector(viewDidLoad), @selector(ysc_viewDidLoad))
*/
#ifndef SWIZZLING_CLASS_METHOD
#define SWIZZLING_CLASS_METHOD(clazz, originalSelector, swizzledSelector) { \
Method originalMethod = class_getInstanceMethod(clazz, originalSelector); \
Method swizzledMethod = class_getInstanceMethod(clazz, swizzledSelector); \
BOOL isAddedMethod = class_addMethod(clazz, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); \
if (isAddedMethod) { \
class_replaceMethod(clazz, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); \
} \
else { \
method_exchangeImplementations(originalMethod, swizzledMethod); \
} }
#endif
/**
* 代码段简写
*/
#define RGBA(r, g, b, a) [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:a]
#define RGB(r, g, b) RGBA(r,g,b,1.0f)
#define RGB_GRAY(c) RGBA(c,c,c,1.0f)
#define RANDOM_INT(from,to) ((int)((from) + arc4random() % ((to)-(from) + 1))) //随机数 [from,to] 之间
#define GET_NSERROR_MESSAGE(e) ((NSError *)e).userInfo[NSLocalizedDescriptionKey] //=e.localizedDescription
#define KEY_WINDOW [UIApplication sharedApplication].keyWindow
#define FUNCTION_NAME [NSString stringWithUTF8String:__FUNCTION__]
#define IS_NIB_EXISTS(nib) [[NSFileManager defaultManager] fileExistsAtPath:[[NSBundle mainBundle] pathForResource:nib ofType:@"nib"]]
#define CREATE_NSERROR_WITH_Code(c,m) [NSError errorWithDomain:@"YSCKit" code:c userInfo:@{NSLocalizedDescriptionKey : m}]
#define CREATE_NSERROR(m) CREATE_NSERROR_WITH_Code(0,m)
#define PRINT_DEALLOCING NSLog(@"[%@] is deallocing...",NSStringFromClass(self.class));
#define DEPRECATED_MARK(_instead_msg) NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, _instead_msg) // 用于标示变量或方法已经过期了
/**
* 1. if (NSOrderedAscending != COMPARE_VERSION(v1,v2)) { //v1 >= v2 }
* 2. if (NSOrderedDescending == COMPARE_VERSION(v1,v2)) { //v1 > v2 }
* 3. if (NSOrderedAscending == COMPARE_VERSION(v1,v2)) { //v1 < v2 }
*/
#define COMPARE_VERSION(v1,v2) [v1 compare:v2 options:NSNumericSearch]
#define COMPARE_CURRENT_VERSION(v) COMPARE_VERSION([[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"], (v))
#define APP_SKIP_VERSION(v) [NSString stringWithFormat:@"APP_SKIP_VERSION_%@", v]
#define APP_LAUNCH_VERSION(v) [NSString stringWithFormat:@"APP_LAUNCH_VERSION_%@", v]
/**
* @brief 关闭performSelector的leak警告提示
*
* @usage:
* PERFORM_SELECTOR_WITHOUT_LEAKWARNING(
* [_target performSelector:_action withObject:self]
* );
*
* OR
*
* id result;
* PERFORM_SELECTOR_WITHOUT_LEAKWARNING(
* result = [_target performSelector:_action withObject:self]
* );
*/
#ifndef PERFORM_SELECTOR_WITHOUT_LEAKWARNING
#define PERFORM_SELECTOR_WITHOUT_LEAKWARNING(block) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
if (block) { \
block(); \
} \
_Pragma("clang diagnostic pop") \
} while (0)
#endif
/**
* 注册通知与发送通知
*/
//注册通知
#define ADD_OBSERVER_WITH_OBJECT(_selector, _name, _object) \
([[NSNotificationCenter defaultCenter] addObserver:self selector:_selector name:_name object:_object])
#define ADD_OBSERVER(_selector,_name) \
ADD_OBSERVER_WITH_OBJECT(_selector, _name, nil)
//发送通知
#define POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, _object, _info) \
([[NSNotificationCenter defaultCenter] postNotificationName:_name object:_object userInfo:(_info)])
#define POST_NOTIFICATION(_name) \
POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, nil, nil)
#define POST_NOTIFICATION_WITH_OBJECT(_name, _object) \
POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, _object, nil)
#define POST_NOTIFICATION_WITH_INFO(_name, _info) \
POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, nil, _info)
//移除通知
#define REMOVE_OBSERVER(_name) \
([[NSNotificationCenter defaultCenter] removeObserver:self name:_name object:nil])
#define REMOVE_ALL_OBSERVERS(_self) \
([[NSNotificationCenter defaultCenter] removeObserver:_self])
/**
* @usage:
* YSCBenchmark(^{
* // code
* }, ^(double ms) {
* NSLog(@"time cost: %.2f ms",ms);
* });
*/
static inline void YSCBenchmark(void (^block)(void), void (^complete)(double ms)) {
// <QuartzCore/QuartzCore.h> version
/*
extern double CACurrentMediaTime (void);
double begin, end, ms;
begin = CACurrentMediaTime();
block();
end = CACurrentMediaTime();
ms = (end - begin) * 1000.0;
complete(ms);
*/
// <sys/time.h> version
struct timeval t0, t1;
gettimeofday(&t0, NULL);
block();
gettimeofday(&t1, NULL);
double ms = (double)(t1.tv_sec - t0.tv_sec) * 1e3 + (double)(t1.tv_usec - t0.tv_usec) * 1e-3;
complete(ms);
}
/**
* @usage:
* @interface NSObject (MyAdd)
* @property (nonatomic, strong) NSMutableArray *textFields;
* @end
*
* #import <objc/runtime.h>
* @implementation NSObject (MyAdd)
* YSC_DYNAMIC_PROPERTY_LAZYLOAD(textFields, NSMutableArray *, [NSMutableArray new])
* @end
*/
#ifndef YSC_DYNAMIC_PROPERTY_LAZYLOAD
#define YSC_DYNAMIC_PROPERTY_LAZYLOAD(_getter_, _type_, _initObject_) \
- (_type_)_getter_ { \
_type_ target = objc_getAssociatedObject(self, _cmd); \
if ( ! target) { \
target = _initObject_; \
objc_setAssociatedObject(self, _cmd, target, OBJC_ASSOCIATION_RETAIN_NONATOMIC); \
} \
return target; \
}
#endif
/**
* usage:
* @interface NSObject (MyAdd)
* @property (nonatomic, assign) BOOL isError;
* @end
*
* #import <objc/runtime.h>
* @implementation NSObject (MyAdd)
* YSC_DYNAMIC_PROPERTY_BOOL(isError, setIsError)
* @end
*/
#ifndef YSC_DYNAMIC_PROPERTY_BOOL
#define YSC_DYNAMIC_PROPERTY_BOOL(_getter_, _setter_) \
- (void)_setter_:(BOOL)value { \
NSNumber *number = [NSNumber numberWithBool:value]; \
[self willChangeValueForKey:@#_getter_]; \
objc_setAssociatedObject(self, _cmd, number, OBJC_ASSOCIATION_RETAIN); \
[self didChangeValueForKey:@#_getter_]; \
} \
- (BOOL)_getter_ { \
NSNumber *number = objc_getAssociatedObject(self, @selector(_setter_:)); \
return [number boolValue]; \
}
#endif
/**
* Synthsize a dynamic object property in @implementation scope.
* It allows us to add custom properties to existing classes in categories.
*
* @param association ASSIGN / RETAIN / COPY / RETAIN_NONATOMIC / COPY_NONATOMIC
* @warning #import <objc/runtime.h>
* *******************************************************************************
*
* @usage:
* @interface NSObject (MyAdd)
* @property (nonatomic, retain) UIColor *myColor;
* @end
*
* #import <objc/runtime.h>
* @implementation NSObject (MyAdd)
* YSC_DYNAMIC_PROPERTY_OBJECT(myColor, setMyColor, RETAIN_NONATOMIC, UIColor *)
* @end
*/
#ifndef YSC_DYNAMIC_PROPERTY_OBJECT
#define YSC_DYNAMIC_PROPERTY_OBJECT(_getter_, _setter_, _association_, _type_) \
- (void)_setter_:(_type_)object { \
[self willChangeValueForKey:@#_getter_]; \
objc_setAssociatedObject(self, _cmd, object, OBJC_ASSOCIATION_##_association_); \
[self didChangeValueForKey:@#_getter_]; \
} \
- (_type_)_getter_ { \
return objc_getAssociatedObject(self, @selector(_setter_:)); \
}
#endif
/**
* @usage:
* @interface NSObject (MyAdd)
* @property (nonatomic, retain) CGPoint myPoint;
* @end
*
* #import <objc/runtime.h>
* @implementation NSObject (MyAdd)
* YSC_DYNAMIC_PROPERTY_CTYPE(myPoint, setMyPoint, CGPoint)
* @end
*/
#ifndef YSC_DYNAMIC_PROPERTY_CTYPE
#define YSC_DYNAMIC_PROPERTY_CTYPE(_getter_, _setter_, _type_) \
- (void)_setter_:(_type_)object { \
[self willChangeValueForKey:@#_getter_]; \
NSValue *value = [NSValue value:&object withObjCType:@encode(_type_)]; \
objc_setAssociatedObject(self, _cmd, value, OBJC_ASSOCIATION_RETAIN); \
[self didChangeValueForKey:@#_getter_]; \
} \
- (_type_)_getter_ { \
_type_ cValue = { 0 }; \
NSValue *value = objc_getAssociatedObject(self, @selector(_setter_:)); \
[value getValue:&cValue]; \
return cValue; \
}
#endif
/**
* @usage:
* @weakiy(self)
* [self doSomething^{
* @strongiy(self)
* if (!self) return;
* ...
* }];
*/
#ifndef weakiy
#if DEBUG
#if __has_feature(objc_arc)
#define weakiy(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
#else
#define weakiy(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
#endif
#else
#if __has_feature(objc_arc)
#define weakiy(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
#else
#define weakiy(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
#endif
#endif
#endif
#ifndef strongiy
#if DEBUG
#if __has_feature(objc_arc)
#define strongiy(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
#else
#define strongiy(object) autoreleasepool{} __typeof__(object) object = block##_##object;
#endif
#else
#if __has_feature(objc_arc)
#define strongiy(object) try{} @finally{} __typeof__(object) object = weak##_##object;
#else
#define strongiy(object) try{} @finally{} __typeof__(object) object = block##_##object;
#endif
#endif
#endif
#endif /* YSCMacros_h */