Aspects–ios AOP-oriented library for tangent-plane programming

Source: Internet
Author: User

Brief introduction

A simple and efficient library that enables iOS to support AOP-oriented programming. It can help you change the behavior of a class effectively without changing the code of a class or class instance. The traditional AOP approach to iOS is much simpler and more efficient. Support is performed before/after the method execution or alternative to the original method. Used to be Part of Pspdfkit, Pspdfkit, has applications in both Dropbox and Evernote, and is now available separately and open to everyone.

Project home: Aspects

Latest example: Click to download

Note: AOP is a design pattern that is completely different from OOP. For more information, refer to this: AOP Baidu Encyclopedia

Quick Start Environment requirements
    • ARC
    • IOS 7 + or OS X 10.7 +
Installation using CocoaPods installation
Pod "aspects"
Manual Installation

Drag the file aspects.h/m to the project.

Usage Application Scenario

The aspects is used to support AOP (aspect-oriented programming) patterns that partially address specific problems that the OOP (object-oriented) pattern cannot solve. Specifically, those that are cross-defined in multiple methods, which cannot or are difficult to classify effectively, such as:

    • Permission checking is always required whenever a user obtains server-side data through a client.
    • Whenever the user interacts with the market, it should always be more user-specific to purchase references or related products accordingly.
    • All operations that require logging.
Interface overview

Aspects to NSObject 扩展了下面的方法 :

Adds a block of code to a method of a specified class before/after it is executed. All objects of this class will work.//////@param The Block  method is added to the hook, aspectes copies the signature information of the method.///The first parameter will be ' Id<aspectinfo> ', the remaining parameters are the parameters of this called method.////These parameters are optional and will be used to pass parameters to the location of the block code blocks.///You even use one without any parameters or only one ' id< Aspectinfo> ' parameter blocks of block code.//////@ Note Adding hooks to static methods is not supported.///@return Returns a unique value that is used to cancel this hook. + (id<aspecttoken>) aspect_ Hookselector: (SEL) selector                      withoptions: (aspectoptions) Options                       Usingblock: (ID) block                            error: (Nserror * *) error;///adds a block of code to a specified object before/after a method executes/replaces/after. works only on the current object. -(id<aspecttoken>) Aspect_hookselector: (SEL) selector withoptions: (aspectoptions) options Usingblock: (ID) Block Error: (NSERROR *) error; Undo a aspect hook.///@return YES to revoke the success, otherwise return NO. id<aspecttoken> aspect = ...; [Aspect remove];

All calls will be thread-safe. Aspects uses the OBJECTIVE-C message forwarding opportunity to have a certain performance cost. All for overly frequent calls, it is not recommended to use aspects.aspects more suitable for views/controller-related calls with no more than 1000 times per second of code.

code example

You can use aspects to dynamically add logging functionality when you debug your app.

[Uiviewcontroller aspect_hookselector: @selector (viewwillappear:) withoptions:aspectpositionafter usingBlock:^ (ID <AspectInfo> Aspectinfo, BOOL animated) {    NSLog (@ "Controller%@ will be displayed:%tu", aspectinfo.instance, animated);} Error: NULL];

With it, the settings for the analysis feature are simple:

Https://github.com/orta/ARAnalytics

You can use it in your test case to check if a method is actually called (when it comes to inheritance or class expansion, it is very easy to see a case where a parent/subclass method is not called as expected):

-(void) testexample {    TestClass *testclass = [TestClass new];    TestClass *testclass2 = [TestClass new];    __block BOOL testcallcalled = NO;    [TestClass aspect_hookselector: @selector (testcall) withoptions:aspectpositionafter usingblock:^{        testcallcalled = YES;    } Error:null];    [TestClass2 testcallandexecuteblock:^{        [TestClass testcall];    } Error:null];    Xctasserttrue (testcallcalled, @ "Call Testcallandexecuteblock must call Testcall");}

It's really going to do a lot of good to debug your app. Here I want to know exactly when to tap a gesture's state to change (if it's a subclass of your custom gesture, you can rewrite the setState: method to achieve a similar effect; but the real purpose here is to capture all of the various types of controls by tapping gestures To accurately analyze the cause):

[_singletapgesture aspect_hookselector: @selector (setState:) withoptions:aspectpositionafter usingblock:^ (id< Aspectinfo> aspectinfo) {    NSLog (@ "%@:%@", Aspectinfo.instance, aspectinfo.arguments);} Error:null];

Here is an example of when you are monitoring when a modal display controller disappears. You can usually write a subclass to achieve similar results, but using aspects can reduce your code size effectively:

@implementation Uiviewcontroller (dismissactionhook) // Would add a dismiss action once the controller gets dismissed. -(void) Pspdf_addwilldismissaction: (void (^) (void)) Action {    ! = NULL);    [Self aspect_hookselector: @selector (viewwilldisappear:) withoptions:aspectpositionafter usingblock:^ (id< Aspectinfo> aspectinfo) {        if  ([aspectinfo.instance isbeingdismissed]) {            Action ();        }    } Error:null];} @end

Benefits for debugging

Aspectes will automatically tag itself, and it's easy to see whether a method has been called in the call stack:

Use aspects on a method that returns a value other than void

You can use the Nsinvocation object class to customize the return value:

[Pspdfdrawview aspect_hookselector: @selector (shouldprocesstouches:withevent:) withoptions:aspectpositioninstead usingblock:^ (id<aspectinfo> info, nsset *touches, Uievent *Event) {        //invokes the original implementation of the method.BOOL processtouches; Nsinvocation*invocation =info.originalinvocation;        [Invocation invoke]; [Invocation Getreturnvalue:&Processtouches]; if(processtouches) {processtouches= Pspdf_stylusshouldprocesstouches (Touches,Event); [Invocation Setreturnvalue:&Processtouches]; }} Error:null];


Compatibility and limitations
    • When applied to a class (using a class method to add hooks), you cannot hook the same method of the parent and child classes at the same time; however, this restriction is not restricted when applied to the example of a class (using instance methods to add hooks).
    • When using KVO, it is best to add an observer after the Aspect_hookselector: call, or it may cause a crash.

Aspects–ios AOP-oriented library for tangent-plane programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.