Introduction: The project requires a statistical analysis of button click events, and now the project is to add a click event in the response code of the button, very cumbersome. Therefore, the use of AOP (aspect-oriented programming), the statistical business logic to pull out of the unified.
Open source libraries added to the project: https://github.com/steipete/Aspects
Method swizzling uses runtime to swap the function sel a,imp A with sel b,imp B, a black magic that makes it possible to pull away from the business logic.
For more information, refer to: http://www.cocoachina.com/ios/20150120/10959.html
My process is to create a new class to handle AOP, called the Aspect class.
+ (void) Load {
[Super load];
[Aspect sharedinstance];
}
+ (Instancetype) sharedinstance {
static Cgaspect *_shared = nil;
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
_shared = [[Cgaspect alloc] init];
});
return _shared;
}
-(Instancetype) init
{
self = [super init];
if (self) {
[Self Cg_hook_uibutton];
}
return self;
}
-(void) Cg_hook_uibutton {
[UIButton aspect_hookselector: @selector (sendAction:to:forEvent:) withoptions:0 usingblock:^ (id<aspectinfo> Info) {
UIButton *BTN = [info instance];
NSString *str = Btn.buriedpointtag;
if (Str.length > 0) {
The module that handles the statistics here
}
} Error:null];
}
The main description of the hook method, apects the hook has a good package, the first parameter is a need to hook the SEL, the second parameter is an enumeration state, indicating your hook method and the third parameter (block) execution order, see enumeration description. The third block parameter can be obtained with info, which can be obtained by [info instance] to the invoked instance object, where it is a button.
The Btn.buriedpointtag property is the label of the button specifically used to handle statistics, and of course you can also use the native tag tag, which I'm mainly here to completely pull away from the logic here.
Here's how to add a buriedpointtag to a button
-(NSString *) Buriedpointtag
{
Return Objc_getassociatedobject (self, uibutton_buriedpoint_key);
}
-(void) Setburiedpointtag: (NSString *) Buriedpointtag
{
Objc_setassociatedobject (self, uibutton_buriedpoint_key, Buriedpointtag, objc_association_retain_nonatomic);
}
This makes it easy to do the statistics of the button, of course, your product to the other control also do statistics, you still need to go to the extra processing, you can also use this method for other types of statistical business to pull away, the specific situation needs to see whether the need to do so.
Applications in the AOP and Method swizzling project in iOS