iOS Development--Debugging &xcode common debugging techniques

Source: Internet
Author: User
Tags print object throw exception

Xcode common Debugging Tips Enable Nszombie Objects (Turn on Zombie object)The Enable Nszombie objects is probably the most useful debugging technique in the entire Xcode development environment. This technique is very very easy to trace to the problem of repeated release. This technique prints the class that indicates the duplicate release and the memory address of the class in a very concise manner. How do I turn on zombie objects? First Open "Edit Scheme" (or via Hotkey?<), then select the Diagnostics tab and tick the Enable Nszombie objects option. Now we can turn off arc to test the problem of repeated releases, anomalies, and more easily generated crashs, but even if arc is turned on, repeated releases and memory-related CRASHS often occur. Now suppose we make some mistakes that lead to repeated releases to see what's going to happen.
1 uiview* view = [[[UIView alloc] init] autorelease];    2 // ...    3 // Do something with view...clearly forgetting the It has been autoreleased.    4 //   5 [view release];  
Now that the code is running, a duplicate release will occur, and the program will crash in the main function, as follows: Enable Nszombie objects will make the debugger look like this: this example looks very small, but for a big project through the Enable Nszombie Objects printed information is very useful.   Add Global Breakpoint (Global Breakpoint) for all exceptionsWhen your app is abnormal or crashes, one of the things that Xcode likes to do is jump directly to the main function, just like the first one in the debugging technique. It would be nice if the exception or crash could stay where the anomaly or crash occurred. Fortunately, there is a way to do that. Xcode has a nice feature called an exception breakpoint that allows us to place a breakpoint where the exception occurs when the exception occurs. You can specify a specific exception or you can specify all exceptions. How do I turn on an abnormal breakpoint? The project switches to the Exception browser window, click on the "Add Breakpoint" button on the left, and select "Add Exception Breakpoint" to ensure that all exceptions can be captured. Now that the exception occurs, the debugger does not jump directly to the main function, but instead stops at the place where the exception occurred. This breakpoint gives us a very good starting point to debug the exception, we do not have to go through the generation to buy to find where the anomaly occurred. Static Analyzer (stationary analysis)Static Analyzer is a very good tool to find compiler warnings that do not prompt problems and errors in some personal internal error leaks and dead storage (which are not used by assigned value variables). This approach can greatly improve memory usage and performance, as well as improve the overall stability and code quality of your application. How do I open the static Analyzer? Open the Xcide Product menu and select the Analyzer option (or use the hotkey?). Shift B). As you can see below, Static Analyzer captures possible problems in any application and then displays them with a blue warning. We can also set up our app to automatically turn on Static Analyzer when we compile the app, open the project projects file, and set "Run Static Analyzer" to Yes, such as: condational Breakpoints (conditional breakpoint)The last debugging technique is a conditional breakpoint, which is just a normal breakpoint, and the program stops when the variable satisfies a certain condition. This debugging technique is useful when you want to capture a specific value of a variable in a loop, or something that doesn't happen often, without having to stop at each iteration to see it. How do I turn on conditional variables? Just add a normal breakpoint, then right click on the breakpoint to select "Edit Breakpoint", then opened a breakpoint editor, you can set the breakpoint conditions (and some other breakpoint settings), and then choose "Done", this debugging technique is very simple. Respondstoselector method for overriding object

It is not easy to find the cause when exc_bad_access the bug when the iphone is being developed.


First of all, exc_bad_access this error, so to speak, 90% of the source of error is to release an object that has been released, or to manipulate an object in a sequence that has been modified in the loop code. Although using the nszombieenabled variable can help you find the problem, there are times when you can't locate the problem even by setting the nszombieenabled variable, you can try Override the Respondstoselector method of object to display the last object accessed before exec_bad_access, following the specific steps:

A, in each class and in other C flags, add-D _for_debug_ (remember to add this tag only under DEBUG configuration). So when your program crashes, Xcode's console will accurately record the last-run method of object. Implementation file (. m,.mm) file, add the following code:

-(BOOL) Respondstoselector: (SEL) aselector {      printf ("SELECTOR:%s\n", [ Nsstringfromselector (Aselector) utf8string]);       return [Super Respondstoselector:aselector];  }

b, and add-D _for_debug_ in other C flags (remember to add this tag only under DEBUG configuration). So when your program crashes, Xcode's console will accurately record the last-run method of object.

get Xcode to feed back enough information

Find arguments in Edit–>scheme, add it in environment variables
Set the following 2 values to Yes
Nsautoreleasefreedobjectcheckenabled
Nsdebugenabled
This method is very useful and it is recommended to add this setting when building a project

Unrecognized selector Send to INSTANCD quick locationIn the Debug menu, Breakpoints->create symbolic Breakpoint fill in the following method signature in symbolic
    1. -[nsobject (NSObject) Doesnotrecognizeselector:]
Once the setup is complete, you will be positioned to the specific code after encountering a similar error.

You can also do this by setting a breakpoint at the system throw exception: the same as the meaning above

The program does not know where to run crash, and crash is difficult to reproduce.

The conservative approach is to set breakpoints before the system throws an exception. (specifically, set breakpoints at Objc_exception_throw.) )


the setup steps are:

1. In XCode press CMD + 6, enter the breakpoint Management window;
2. Then click + On the lower right to add the new symbolic breakpoint.
3. In the Symbol field, enter: Objc_exception_throw, then click Done to finish.


High-level loading technology-gdb

XCode has built-in gdb, and we can use the GDB command at the command line to debug our program. Here are some common commands and debugging tips.

po Command : for the abbreviation of print object, displays the text description of the objects (displays the string information obtained from the object's description message).

Like what:


, I use the PO command to display a nsdictionary content. Note on the left we can see some information about Dict: 3 key/value pairs, which shows the amount of data that the dict contains, and the expanded information shows the ISA hierarchy (that is, class and metaclass structure relationships). We can right-click on the left side of the dict and check "Print Description of" Dict "", you can output dict details in the console:

Printing Description of dict: {type= Immutable Dict, Count =3, Entries=0: {contents =" First"} = {contents =" One"}      1: {contents ="Second"} = {contents =" Both"}      2: {contents ="Third"} = {contents ="three"}  }  


Print command : Somewhat similar to formatted output, you can output different information about an object:

Such as:

(GDB) print (char *) [[dict description] cstringusingencoding:4]

    • $ = 0x1001159c0 "{\ n first = one;\n second = two;\n third = three;\n}"

(GDB) print (int) [Dict Retaincount]

    • $ = 1

(GDB)

Note: 4 is the value of nsutf8stringencoding.

Info Command : we can see where the memory address resides

For example, "info symbol memory Address" to obtain the memory address of the symbol related information:

(GDB) Info symbol 0X00000001000017F7

    • Main + 343 in section Lc_segment.__text.__text of/users/luozhaohui/library/developer/xcode/deriveddata/ Runtimesystem-anzdlhiwvlbizpfureuvenvmatnp/build/products/debug/runtimesystem

For example, "Info line * Memory address" can be used to obtain the memory address of the code lines related information:

(GDB) Info line *0x00000001000017f7

    • Line/USERS/LUOZHAOHUI/DOCUMENTS/STUDY/RUNTIMESYSTEM/RUNTIMESYSTEM/MAIN.M ' starts at address 0x1000017f7 and Ends at 0x10000180a.


Show command : displays GDB-related information. For example: Show version displays GDB release information

(GDB) Show version

    • GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon 8 20:32:45 UTC 2011)
    • Copyright 2004 Free Software Foundation, Inc.
    • GDB is free software, covered by the GNU general public License, and you are
    • Welcome to change it and/or distribute copies of it under certain.
    • Type "Show copying" to see the conditions.
    • There is absolutely no warranty for GDB. Type "Show warranty" for details.
    • This GDB is configured as "X86_64-apple-darwin".

Help Command : If you forget the syntax of a command, you can use the helper command name to get assistance information. Example: Help info displays the usage of the info command.

(GDB) Help info

    • Generic command for showing things on the program being debugged.
    • List of Info subcommands:
    • Info address--Describe where symbol SYM is stored
    • Info all-registers--List of all registers and their contents
    • Info args--Argument variables of current stack frame
    • Info AUXV--Display the inferior ' s auxiliary vector
    • Info breakpoints--Status of user-settable breakpoints
    • Info Catch--Exceptions that can is caught in the current stack frame
    • Info checkpoints--help
    • Info Classes--All OBJECTIVE-C classes
    • ......
    • Type ' Help info ' followed by info subcommand name for full documentation.
    • Command name abbreviations is allowed if unambiguous.


Common GDB Commands

        • Break NUM sets a breakpoint on the specified line.
        • BT displays all the call stack frames. This command can be used to display the order in which functions are called.
        • Clear removes breakpoints that are set on a specific source file, on a specific line. Its usage is: Clear filename:num.
        • Continue continue to execute the program being debugged. This command is used when the program stops running because of processing a signal or a breakpoint.
        • Display EXPR Displays the value of an expression every time the program stops. An expression consists of a variable defined by a program.
        • The file file loads the specified executable file for debugging.
        • Help NAME displays assistance information for the specified command.
        • Info break Displays the list of current breakpoints, including the number of times the breakpoint was reached.
        • Info files Displays detailed information about the files being debugged.
        • Info func Displays all the function names.
        • Info Local Displays the local variable information in the function.
        • Info prog shows the execution state of the program being debugged.
        • Info var displays all the global and static variable names.
        • Kill terminates the program that is being debugged.
        • The list displays the source code snippet.
        • Make to run the Make tool without exiting GDB.
        • Next executes a line of source code forward without stepping into other functions.
        • Print expr Displays the value of the expression expr.
        • Print-object Printing an Object
        • print (int) name prints a type
        • Print-object [artist description] Call a function
        • Set artist = @ "Test" sets the value of the variable

          • Expr gesturedisabled = 1 setting variable values
          • Whatis view the data type of the variable

iOS Development--Debugging &xcode common debugging techniques

Related Article

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.