My Goddess--Simple and practical iOS code debugging framework

Source: Internet
Author: User

My Goddess--Simple and practical iOS code debugging frameworkFirst, Introduction

The origin of this blog is to take over an already completed project of the company, to do code optimization, project engineering is very large, and introduced a lot of internal SDK, to find out the internal framework of the company, it is not an easy thing, and because this project is developed by many people, in the debugging phase will print a huge amount of debugging information, Make browsing useful information becomes very difficult, more frightening is, a lot of information is debugging in the SDK printing, these are written off is very laborious or impossible, so there are some requirements: first, I need to clearly understand the various controllers between the jump relationship, Need to quickly figure out the ins and outs of each controller in each stroyboard, and secondly, I want to block the redundant log information without changing the debug code of others, making my debug data clearer. So I think of the following solutions, similarly, if you have a better solution or you know the excellent solution, please let me, thank you very much.

second, the tracking program's jump Path

         It's a very easy problem to solve, as we all know, A controller, if you want to show, will walk the life cycle of the viewwillappear this method, we only need to do some hands and feet in this method can be, the realization of two ideas, one is to use the factory design mode, set up factory class controller, Add our debug code to its viewwillappear, but this is not practical for my project, first I'm not sure all controllers will inherit from a parent class, and secondly, when I don't find the source, these classes are already in the company's framework, I can't operate the source code at all. The second scenario is runtime, right, OC at run time, not impossible. For a detailed description of the runtime, the http://my.oschina.net/u/2340880/blog/489072 viewwillappear , in which we add our debug code, which is method swizzing, The code is designed as follows:

Create a new category for Conreoller #import  "Uiviewcontroller+yhbasetest.h" #import  <objc/runtime.h>@ implementation uiviewcontroller  (yhbasetest) +  (void) load {    // Thread that executes only once     static dispatch_once_t oncetoken;    dispatch_ Once (&oncetoken, ^{        class class = [self  class];        // when swizzling a class  method, use the following:        // class  class = object_getclass ((id) self);         //Create two selectors   points to the   system and the function we want to replace         sel originalselector =   @selector (viewwillappear:);         sel swizzledselector  =  @selector (yhbaseviewwillappear:);         //Get method Instance          Method originalmethod = class_getinstancemethod (Class, originalselector);         method swizzledmethod = class_getinstancemethod (class,  swizzledselector)         //Now add the method to          bool didaddmethod =        class_addmethod (class,                         originalSelector,                         method_ Getimplementation (Swizzledmethod),                   &nbSp;     method_gettypeencoding (Swizzledmethod));         //Method Replacement         if  (Didaddmethod)  {             class_replacemethod (class,                                  swizzledSelector,                                  method_getimplementation (OriginalMethod),                                  method_gettypeencoding (OriginalMethod) );         } else {             method_exchangeimplementations (Originalmethod, swizzledmethod);         }    });} #pragma  mark - Method Swizzling-  (void) Yhbaseviewwillappear: (BOOL) animated {// Here's my plus one. Control Debug Lock   Introduction     [self YHBaseViewWillAppear:animated];     yhbaseprocesslog (@ "yhbasetest:viewwillappear: %@",  self);     }
Third, shielding the redundant log information 1, the system of NSLog is a what thing

To defeat our enemies, we should first understand our enemies, we want to block nslog printing, we need to clear what nslog is really a thing.

First, the nslog is defined as follows:

Foundation_export void NSLog (NSString *format, ...) (ns_format_function); Foundation_export void Nslogv (NSString *format, va_list args) ns_format_function (1,0);

There are two functions, one for NSLog printing using a multi-parameter format string, and one for printing with parameter pointers. From here we can see that the system's NSLog is a C-style function, so, we have the idea, we can define a NSLog macro to replace all the NSLog in the project, as follows:

//... is a macro that omits the argument, and the __va_args__ is a system-defined macro that declares the indeterminate parameter, # # NSLOG (...). Yhbasetestlog (__va_args__)
2, to achieve our own nslog

Through the above method, in the absence of the source code, we can replace all the printing in the program, you may wonder how the program will allow us to have two nslog, in fact, it is not magical, to know that the macro is a precompiled instruction, all of these operations are done before the code is compiled, In fact, the program has simply replaced the nslog with our function call, the program only a nslog, this is the strong point of the macro, Civet cat for Prince, good bar.

Let's implement this function as follows:

Don't forget to declare void Yhbasetestlog (NSString *str,...) in the. h file    {//Parameter column va_list list;    Va_start (list, str); This place is a lock and will be introduced later if (![    Yhbasetestlock sharedthesingletion]->_customlock) {//For printing nslogv (str, list); } va_end (list);}

This function does not actually do anything, add a lock judgment, this is all, the core of the control, to our lock it:

. h file @interface yhbasetestlock : nsobject<yhsingletonprocotol>{    @ Public    bool _customlock;    bool _precesslock;} + (void) customlock;+ (void) customunlock;+ (void) processloglock;+ (void) processlogunlock;//.m//Single-case method + (Instancetype) Sharedthesingletion{    static yhbasetestlock * sharedmodel = nil ;     static dispatch_once_t predicate;    dispatch_once ( &predicate, ^{        sharedmodel = [[ yhbasetestlock alloc] init];    });    return  Sharedmodel;} -  (instancetype) init{    self = [super init];     if  (self)  {    //initialization   Default User print all open          _customlock=no;        //default   Our Controller's print screen         _ Precesslock=yes;    }    return self;} setting of the response + (void) Customlock{    [yhbasetestlock sharedthesingletion]->_customlock=yes ;} + (void) customunlock{      [yhbasetestlock sharedthesingletion]->_ Customlock=no;} + (void) Processloglock{     [yhbasetestlock sharedthesingletion]->_precesslock =yes;} + (void) Processlogunlock{    [yhbasetestlock sharedthesingletion]->_precesslock=no;}
Four, take a look at our masterpiece.

After doing the above work, we in the appdelegate as follows simple configuration:

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {//    Override point for customization after application launch.    Add user to print lock [Yhbasetestlock customlock];    To unlock the process printing [Yhbasetestlock processlogunlock]; return YES;}

We do the following tests:

@interface Viewcontroller () @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload];   Additional setup after loading the view, typically from a nib.    NSLog (@ "111111111111111111111111111111111111111111111111111111111111111");    [Yhbasetestlock Customunlock];    NSLog (@ "This is useful information:%@==%d", @ "See Me Oh", __line__);    [Yhbasetestlock Customlock]; NSLog (@ "32123213123214412312312");}

I printed some interference information before and after the useful information in Viewcontroller, and I can see that this nslog format is fully compatible with the system, unlocked and locked before and after printing useful information, the result is as follows:

As you can see, we have shielded the useless print and printed the program's jump process. Most importantly, we have no changes to the source code, without affecting the development of other people in conflict.


This blog at the beginning, I call my Goddess, really, this method has helped me a lot of work, in my understanding of the project's structural framework, each debug printing in the control area roll out a piece of information really let me dizzy brain swelling, now a cool, spirit is also refreshing a lot, ^_^.



My Goddess--Simple and practical iOS code debugging framework

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.