Some debugging techniques for Xcode are collected

Source: Internet
Author: User
Tags print object

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:

[CPP] View plaincopyprint?

Printing Description of Dict:

<cfbasichash 0x1001149e0 [0x7fff7e27ff40]>{type = Immutable dict, Count = 3,

Entries =

0: <cfstring 0x100002458 [0x7fff7e27ff40]>{contents = "First"} = <cfstring 0x100002438 [0x7fff7e27ff40]>{ Contents = "One"}

1: <cfstring 0x100002498 [0x7fff7e27ff40]>{contents = "second"} = <cfstring 0x100002478 [0x7fff7e27ff40]>{ Contents = "Both"}

2: <cfstring 0x1000024d8 [0x7fff7e27ff40]>{contents = "third"} = <cfstring 0x1000024b8 [0x7fff7e27ff40]>{ Contents = "Three"}

}

(GDB)


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

Such as:

[CPP] View plaincopyprint?

(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:

[CPP] View plaincopyprint?

(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:

[CPP] View plaincopyprint?

(GDB) Info line *0x00000001000017f7

Line "/USERS/LUOZHAOHUI/DOCUMENTS/STUDY/RUNTIMESYSTEM/RUNTIMESYSTEM/MAIN.M" starts at address 0x1000017f7 < Main+343> and ends at 0x10000180a <main+362>.


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

[CPP] View plaincopyprint?

(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.

[CPP] View plaincopyprint?

(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.

(GDB)


Set breakpoints at System throw exception

Sometimes our program does not know where to go to crash, and crash is difficult to reproduce. It is a conservative practice to set breakpoints before the system throws an exception, specifically to set breakpoints at Objc_exception_throw . Set the steps to: First in XCode Press CMD + 6, go to the Breakpoint Management window, then click on the lower right of the +, add a new symbolic breakpoint, enter in the Symbol column:objc_exception_throw, and then click D One, complete. This way, in Debug mode, if the program is about to throw an exception, it can be interrupted at the point where the exception was thrown. For example, in the previous code, I let [firstobjctcrashtest]; Throws an exception. After setting a breakpoint at Objc_exception_throw, the program can break at that code and we know where the code is going wrong.


  1. Command explanation
  2. Break NUM sets a breakpoint on the specified line.
  3. BT displays all the call stack frames. This command can be used to display the order in which functions are called.
  4. Clear removes breakpoints that are set on a specific source file, on a specific line. Its usage is: Clear filename:num.
  5. Continue continue to execute the program being debugged. The command is used in the program because of processing a signal or breakpoint
  6. Causes the stop run time.
  7. Display EXPR Displays the value of an expression every time the program stops. An expression consists of a variable defined by a program.
  8. The file file loads the specified executable file for debugging.
  9. Help NAME displays assistance information for the specified command.
  10. Info Break Displays the list of current breakpoints, including the number of times the breakpoint was reached.
  11. Info files Displays detailed information about the files being debugged.
  12. Info func Displays all the function names.
  13. Info Local Displays the local variable information in the function.
  14. Info prog shows the execution state of the program being debugged.
  15. Info var displays all the global and static variable names.
  16. Kill terminates the program that is being debugged.
  17. The list displays the source code snippet.
  18. Make to run the Make tool without exiting GDB.
  19. Next executes a line of source code forward without stepping into other functions.
  20. Print expr Displays the value of the expression expr.
  21. Print-object Printing an Object
  22. Print (int) name prints a type
  23. Print-object [artist description] Call a function
  24. Set artist = @"Test" sets the value of the variable
  25. Whatis view the data type of the variable

 crash's problem. Crash most of the two, one is signal sigabrt, probably means to send a message there is a problem, the signal lost. This kind of crash in fact is very good positioning, crash after directly see the console in the last log, such as this paragraph:  2012-03-28 19:26:33.055 tableviewmenudemo[3916:f803] * * * Terminating app due to uncaught exception ' nsinvalidargumentexception ', Reason: '-[__nsarrayi replaceobjectatindex: Withobject:]: Unrecognized selector sent to instance 0x6a3f3d0′ *** first throw call stack:  find the reason field, that's why, Say Nsarray call replaceobjectatindex:withobject:  This method is Nsmutablearry, Nsarray does not have this method. The signal was lost, so crash. 0x6a3f3d0  is the memory address of the problem, check the memory address or search down the method is better positioning. &NBSP;&NBSP;XCODE4 also has a better use of positioning method, is to set a exception breakpoint just fine.   See figure in the left column of the project to select Breakpoint Navigator, click the following + sign to add a exception breakpoint, and then run try again, crash, is not directly positioned to the line of code? Then, according to the log in the console to modify the location.   Here is another kind of crash, exc_bad_access, this is a headache, because crash, it may be earlier than a certain variable released, and now access problems. No logs were displayed in the console.   Here light joins exception breakpoint is not enough, XCODE4 also a lovely place, open scheme option select Editscheme.     then click on the graph to enable Zombie objects and malloc stack, and remember that it is usually only in the position Exc_bad_acCess time only check, do not have anything to hook up.   So run again, if it is stopped at exception breakpoint, you can enter in the console: C (continue) press ENTER to continue running until crash. See if the console has a similar error message log with SIGABRT, and what you know behind the location.   If there is no log, enter the PO$EAX$EAX flag in the console error, suitable simulator, real machine with $r0 (say exc_bad_access This error simulator positioning on the line), you can also input such as: po[$eaxname]po[$ Eaxreason] and other instructions to see the error other information (note that there is no semicolon after square brackets). Then, there was no then.   also to add points, the process of development of the program should pay more attention to the issue navigator in the left column of the warning message, XCODE4 will not only warn, but also the majority of the proposed solution, to avoid unnecessary crash behind.    if the program crash, the first time to focus on the Debug navigator in the execution of information, pull the slider to the right to see more call information, according to this can roughly imagine what method to invoke or what to do crash.    

1. Using zombie variables (nszombieenabled)

2. 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, even by setting the nszombieenabled variable, you can't locate the problem, You can try overriding the Respondstoselector method of object, which shows 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:
[CPP]
-(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.

3. Let Xcode feedback 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

4. Set Global Exception Breakpoint

When a program throws an exception, it often needs to navigate to the exception
Type shortcut cmd + 6 to enter the breakpoint window, click on the "+" button in the lower left corner and select the "Add Exception Breakpoint" entry for the popup box as shown in:

Then use the default settings, click the "Done" button, set the global exception breakpoint is complete

Some debugging techniques for Xcode are collected

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.