AOP: Aspect Oriented Programming

What is AOP

  • A technique for unified maintenance of program functions by means of precompilation and runtime dynamic proxies
  • AOP is a continuation of OOP, a derived paradigm of functional programming

Second, THE advantages of AOP

  • Isolate parts of business logic
  • Reduce coupling between parts of business logic
  • Improve application reusability
  • Improved development efficiency

AOP in iOS application – Runtime

Using iOS Runtime, we can do a lot of graft, which reminds people of Method Swizzle first. For Method Swizzle, there is no description here, but you can learn more about it by yourself

Aspects

An iOS AOP library that is simple and enjoyable to use


(1) Basic usage

+ (id<AspectToken>)aspect_hookSelector:(SEL)selector
                           withOptions:(AspectOptions)options
                            usingBlock:(id)block
                                 error:(NSError **)error;

- (id<AspectToken>)aspect_hookSelector:(SEL)selector
                           withOptions:(AspectOptions)options
                            usingBlock:(id)block
                                 error:(NSError **)error;
Copy the code

AspectPositions

typedef NS_OPTIONS(NSUInteger, AspectOptions) { AspectPositionAfter = 0, // Call (default) AspectPositionInstead = 1 after the original implementation, // Replace the original implementation AspectPositionBefore = 2, / / before the original implementation call AspectOptionAutomaticRemoval = 1 < < 3 after removing the Hook} / / execution time;Copy the code

AspectInfo

@protocol AspectInfo <NSObject>
- (id)instance;

- (NSInvocation *)originalInvocation;

- (NSArray *)arguments;
@end
Copy the code

(2) Aspects buried actual combat

/ * * statistics page views * / [UIViewController aspect_hookSelector: @ the selector (viewDidAppear withOptions) : AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo){ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSString *className = NSStringFromClass([[aspectInfo instance] class]); [self doSomething]; }); } error:NULL];Copy the code

(3) Attention to use

  • Aspects use Objective-C message forwarding opportunities, which have a performance cost, so they are not recommended for overly frequent calls
  • When applied to a class (using a class method to add hooks), you cannot hook the same method of the parent class and its subclass at the same time, otherwise it will cause looping problems. However, when applied to an example of a class (using instance methods with hooks), this restriction is not applied.
  • When using KVO, it is best to add an observer after the aspect_hookSelector: call, otherwise it may cause a crash