1,默認(rèn)的初始化數(shù)據(jù),在初始化方法中進行設(shè)置
比如:NSInterge _selectedIndex;
默認(rèn)情況下設(shè)置為 _selectedIndex = 1;
如果在 viewDidload 方法中進行默認(rèn)是的設(shè)置 ,外界在設(shè)置 _selectedIndex = 2 的時機在 viewDidload 之前,則這次的設(shè)置就會被重置為 1。
因此,初始化的默認(rèn)值推薦在初始化中進行設(shè)置
XMNetworking
2,隊列寫法
static dispatch_queue_t xm_request_completion_callback_queue() {
static dispatch_queue_t _xm_request_completion_callback_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_xm_request_completion_callback_queue = dispatch_queue_create("com.xmnetworking.request.completion.callback.queue", DISPATCH_QUEUE_CONCURRENT);
});
return _xm_request_completion_callback_queue;
}
上面的這種書寫方式,便于之后的隊列調(diào)用,如:
dispatch_async(xm_request_completion_callback_queue(), ^{
completionHandler(nil, serializationError);
});
3,信號量:使用宏定義
dispatch_semaphore_t _lock;
_lock = dispatch_semaphore_create(1);
#define XMLock() dispatch_semaphore_wait(self->_lock, DISPATCH_TIME_FOREVER)
#define XMUnlock() dispatch_semaphore_signal(self->_lock)
4,block 使用 宏 調(diào)用
#define XM_SAFE_BLOCK(BlockName, ...) ({ !BlockName ? nil : BlockName(__VA_ARGS__); })
// 調(diào)用:
XM_SAFE_BLOCK(self.requestProcessHandler, request);
AOP 中的方法替換寫法:
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(setCachePolicy:);
SEL swizzledSelector = @selector(ag_setCachePolicy:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (success) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
多個方法需要替換,可以使用下面方式
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSArray *selStringsArray = @[@"reloadData", @"reloadRowsAtIndexPaths:withRowAnimation:", @"deleteRowsAtIndexPaths:withRowAnimation:", @"insertRowsAtIndexPaths:withRowAnimation:"];
[selStringsArray enumerateObjectsUsingBlock:^(NSString *selString, NSUInteger idx, BOOL *stop) {
NSString *mySelString = [@"sd_" stringByAppendingString:selString];
Method originalMethod = class_getInstanceMethod(self, NSSelectorFromString(selString));
Method myMethod = class_getInstanceMethod(self, NSSelectorFromString(mySelString));
method_exchangeImplementations(originalMethod, myMethod);
}];
});
}