AOP programming concept in objective-C
In the software industry, AOP is short for aspect oriented programming. It is a derivative model of functional programming. A technology that implements unified maintenance of program functions by means of pre-compilation and dynamic proxies during runtime. Its main functions include logging, Performance Statistics, security control, transaction processing, and exception handling. The main intention is to divide the log records, Performance Statistics, security control, transaction processing, Exception Processing and other codes from the business logic code. By separating these behaviors, we hope that they can be independent into non-guided business logic methods, and thus change these behaviors without affecting the business logic code.
Performance
Add the Execution Code before and after the FUNA Method
[[XYAOP sharedInstance] interceptClass:[Test class] beforeExecutingSelector:@selector(funa) usingBlock:^(NSInvocation *invocation) { NSLog(@"funa before"); }];[[XYAOP sharedInstance] interceptClass:[Test class] afterExecutingSelector:@selector(funa) usingBlock:^(NSInvocation *invocation) { NSLog(@"funa after"); }];
When we execute FUNA, the following results are output:
2014-10-28 17:31:01.435 testaop[7609:290860] funa before2014-10-28 17:31:01.436 testaop[7609:290860] funa run2014-10-28 17:31:01.436 testaop[7609:290860] funa after
Implementation Principle
Use objective-C's powerful runtime.
We know that when sending a method to an object, if the current class and parent class do not implement this method, the forwarding process will be followed.
- Dynamic Method resolution-> fast message forwarding-> Standard Message forwarding
If you are confused, search for "objective-C message forwarding ".
After learning about message forwarding, we have come to the idea of AOP. We will first kill the original method FUNA, so that when sending methods to objects, we will go through the forwarding process, then we hook up the object's fast message forwarding method, point the object implementing FUNA to our AOP object, and finally execute the before instead after method in the Standard Message forwarding of the AOP object.
For specific code, please download it from GitHub. Remember to give us a star.
Https://github.com/uxyheaven/XYQuickDevelop
Search for xyaop. h In the code
Related Methods
This section describes some of the runtime methods used.
// 给 cls 添加一个新方法BOOL class_addMethod ( Class cls, SEL name, IMP imp, const char *types);// 替换 cls 里的一个方法的实现IMP class_replaceMethod ( Class cls, SEL name, IMP imp, const char *types);// 返回 cls 的指定方法Method class_getInstanceMethod ( Class cls, SEL name);// 设置一个方法的实现IMP method_setImplementation ( Method m, IMP imp);// 返回 cls 里的 name 方法的实现IMP class_getMethodImplementation ( Class cls, SEL name);
AOP programming in objective-C