Xcode Development Tips--debugging

Source: Internet
Author: User
Tags ole

Breakpoint (breakpoint) breakpoints are a very important tool in debugging. Since there is a lot of other code that needs to be executed before some code is executed, it is impossible to execute it with a single step trace, just set a breakpoint where it needs to be paused, and then let the program run. When executed to this breakpoint position, no user intervention is required to pause and return to the integrated debugger. Breakpoints must be on the executable line of code, where the comment, blank line, and variable description are not valid.

I. Overview

1. Master debugging skills, debugging technology

The most basic, the most important debugging means include: single-step tracking, breakpoints, variable observation and so on.

Single-Step Tracking (STEP) is a one-line execution of a program that stops waiting for instructions after each line of statements, so that you can carefully understand the sequence of execution of the program and the various conditions at that time.

Breakpoint (breakpoint) breakpoints are a very important tool in debugging. Since there is a lot of other code that needs to be executed before some code is executed, it is impossible to execute it with a single step trace, just set a breakpoint where it needs to be paused, and then let the program run. When executed to this breakpoint position, no user intervention is required to pause and return to the integrated debugger. Breakpoints must be on the executable line of code, where the comment, blank line, and variable description are not valid. In addition, breakpoints can be set in both the design state and the running debug state. Locate the error based on the breakpoint Debug. In the program development, in order to find the program bug, usually a debugging means, step by step tracking program execution process, according to the value of the variable, find the cause of the error. Set breakpoints in the code that you want to debug, and then follow the preset shortcut key steps. The debug state runs the program and the program executes to a breakpoint where it stops.

2. Memory Leak interpretation

Simple is to apply for a piece of memory space, the use is not released after completion . The general way it behaves is that the longer the program runs, the more memory is consumed, and eventually all the memory is exhausted, and the entire system crashes.     A piece of memory requested by the program, and no pointer to it, then this memory is leaked. In general, the memory leaks that we often say refer to the leaks in heap memory. Heap memory means that the program is allocated from the heap, arbitrarily sized (the size of the memory block can be determined during the program's run time), and the freed memory must be displayed after use. Applications typically use functions such as malloc,realloc,new to allocate a piece of memory from the heap, and after use, the program must be responsible for the corresponding call to free or delete to release the memory block, otherwise the memory cannot be reused, we say this memory leak.

Use the Leaks tool to help view memory leak issues. In the Xcode toolbar,run=> "Run with perfromance tool=>leak in I in phone programming, using NSLog to print out the Retaincount directly on the console is also a way to view the internal leaks, but Xcode provides a more convenient leak tool for developers to use . Http://blog.csdn.net/cloudhsu/archive/2010/07/22/5754818.aspx (important)

Ii. Common Mistakes

1.objective-c exc_bad_access

The

Program encountered a Bug is not scary, most of the problems, through simple Log or code analysis is not difficult to find the reason. However, when encountering exc_bad_access problems in objective-c programming, it is difficult to find the problem by simple and conventional means. This article gives you a common way to find the root cause of exc_bad_access problems. First say exc_bad_access this error, so to speak, 90% of the source of error is the release of an object that has been released.   A simple example to illustrate, first look at a piece of Java code:

    1. public class test{  
    2.         public  static void main (string[] args) { 
    3.                  String s =  "this is a test string";  
    4.                 s =  S.substring (S.indexof ("a"), (S.length ()));  
    5.                  system.out.println (s);  
    6.          } 
    7. } 

This type of writing is common in Java and common, and this does not create any problems. But in the objective-c, there will be an accident, consider this procedure:

    1. #import  <Foundation/Foundation.h>  
    2. int main  (int argc,  C*****t char * argv[])  
    3. {  nsautoreleasepool * pool = [[nsautoreleasepool alloc] init]; 
    4. nsstring* s = [[nsstring alloc]initwithstring:@ "this is a test  String "];&NBSP;
    5.         s = [s  Substringfromindex:[s rangeofstring:@ "a"].location]; //memory leak  
    6.         [s release]; //error release  [pool drain];//exc_bad_access return 0; 
    7. }&NBSP;

This example, of course, is easy to see the problem, if the code is contained in a large logic, it is easy to ignore. objective-c This code has three fatal problems: 1, memory leaks. 2, error free. 3, causing exc_bad_access error.

1, memory leaks. nsstring* s = [[NSString alloc]initwithstring:@ "This is a test string"]; A nsstring Object is created, followed by S = [s substringfromindex:[s rangeofstring:@ "a"].location]; After execution, the object reference that was created disappears, causing a memory leak directly.

2, error free. [s release]; One of the reasons for this problem is a logic error, thinking that S is still the NSString object we created originally. The second is because the NSString object returned from Substringfromindex: (Nsuinteger i) does not need us to release it, it is actually an object that is marked as autorelease by the Substringfromindex method. If we forcibly release it, then it will cause exc_bad_access problems.

3, causing exc_bad_access error. exc_bad_access. Because the NSString object pointed to by S is marked as autorelease, there is already a record in NSAutoreleasePool. But since we released the object in the wrong way, when [pool drain], NSAutoreleasePool once again called the release method on its recorded S object, but this time the S has been released and no longer exists, it directly caused the E Xc_bad_access problem.

So, knowing one of the causes of exc_bad_access, how to locate the problem quickly and efficiently? 1: Add the nszombieenabled environment variable to the project runtime, and set to enable, the c*****ole of XCode will print out the problem description when exc_bad_access occurs. First double-click the executable module under executables in the XCode project, in the pop-up window, Variables to is set in the environment, add nszombieenabled, and set to YES, click to select the check box to enable the change Amount In this way, you will see console output when you run the above objective-c: untitled[3646:a0f] * * *-[cfstring release]: message sent to deallocated instance 0x10010d34 0 This message is a good indication of the location problem. But many times, only this hint is not enough, we need more hints to help locate the problem, then join mallocstacklogging to enable malloc record. When the error occurs, the terminal executes: Malloc_history ${app_pid} ${OBJECT_INSTANCE_ADDR} will receive the corresponding malloc  history, for example, for the previous console output UNTITLED[3646:A0F] * * *-[cfstring release]: message sent to deallocated instance 0x10010d340   We can do it at the terminal The result is as follows:

Buick-wongs-macbook-pro:downloads buick$ malloc_history 3646 0x10010d340 malloc_history report version:2.0 Process: Untitled [3646] Path:/users/buick/desktop/untitled/build/debug/untitled Load address:0x100000000 Identifier: Untitled Version:??? (???) Code type:x86-64 (Native) Parent Process:gdb-i386-apple-darwin [3638] date/time:2011-02-01 15:07:04.181 +0800 OS Versio N:mac OS X 10.6.6 (10j567) Report Version:6 ALLOC 0x10010d340-0x10010d357:thread_7fff70118ca0 |start | Main | Objc_msgsend | Lookupmethod | Prepareformethodlookup | _class_initialize | +[nsstring Initialize] | Objc_msgsend | Lookupmethod | Prepareformethodlookup | _class_initialize | Nxcreatemaptablefromzone | malloc_zone_malloc--Free 0X10010D340-0X10010D357:THREAD_7FFF70118CA0 |start | Main | Objc_msgsend | Lookupmethod | Prepareformethodlookup | _class_initialize | _finishinitializing | Free ALLOC 0x10010d340-0x10010d357:thread_7fff70118ca0 |start | Main | -[nsplaceholderstring initwithstring:] | Objc_mSgsend | Lookupmethod | Prepareformethodlookup | _class_initialize | _class_initialize | +[nsmutablestring Initialize] | Objc_msgsend | Lookupmethod | Prepareformethodlookup | _class_initialize | Nxcreatemaptablefromzone | malloc_zone_malloc--Free 0X10010D340-0X10010D357:THREAD_7FFF70118CA0 |start | Main | -[nsplaceholderstring initwithstring:] | Objc_msgsend | Lookupmethod | Prepareformethodlookup | _class_initialize | _class_initialize | _finishinitializing | Free ALLOC 0x10010d340-0x10010d35f:thread_7fff70118ca0 |start | Main | -[nscfstring Substringwithrange:] | cfstringcreatewithsubstring | __cfstringcreateimmutablefunnel3 | _cfruntimecreateinstance | Malloc_zone_malloc so you can quickly locate the offending code snippet,Note that the last line of the output, although not the ultimate cause of the problem, is close enough to the problem, and probably will find the problem as it finds it. Of course, there are many ways to locate exc_bad_access, which varies with specific problems.

2. _objc_class_$_ errors caused this error for two reasons: 1. The project did not add a coredata framework; 2. Because one or several. m files are not marked (ticked) by the original       The cause of my mistake is caused by the second reason, my solution is to the server-side conflict of several first deleted in the project, and then dragged the deleted files to Xcode, note in the Add file is to remember the hook. If you run the discovery failed to upload *.app problem again, first turn off Xcode, then delete the project's build directory, reopen Xcode again, run the program, and solve the problem.

3. The following error: mainly in the program to add the Chinese symbol; not in English; the error that is caused when you write a program, you must be careful to write it in English.

    1. Link.c:69:error:stray ' \357 ' in program
    2. Link.c:69:error:stray ' \274 ' in program
    3. Link.c:69:error:stray ' \233 ' in program
    4. Link.c:70:error:expected '; ' Before ' Insert_elem '
    5. Link.c:70:error:stray ' \357 ' in program
    6. Link.c:70:error:stray ' \274 ' in program
    7. Link.c:70:error:stray ' \233 ' in program

Third, the IPhone development Lessons learned summary reference

      all UI actions are switched to the main thread. Otherwise, an inexplicable error occurs. In the main thread, Runloop is turned on by default. In a non-main thread, if you want to use Runloop, you must manually turn on Runloop. About Runloop knowledge. For common exec_bad_access,exc_bad_instruction, errors are generally caused by access to objects that have been release. Especially in a thread that accesses objects in the Autorelease library of another thread, especially if you are aware of such problems. Strictly abide by the iphone memory management manual, for objects not created by you, do not exceed the release, otherwise, may lead to the program crash. Sometimes, some seemingly serious bugs, after the N-hard, a variety of ideas after trying fix, then back to analyze the cause of the bug, You will find that the cause of this serious bug is probably caused by a violation of a well-known rule. You know this rule very well, you know it, but when you coding, A little inattention violated it. So it has disastrous consequences. In addition to object-oriented cocoa, iphone programming does not forget the non-object-oriented core Foundation. There are many features in the object-oriented library that you can try to find in the core Foundation. For example: RSA algorithm, MD5 algorithm, SHA1 algorithm, AES encryption algorithm, etc., Cocoa Object Library does not have the corresponding realization, but in core Foundation, all have corresponding realization. NSString class does not have the string encoding gbk,gb2312,gb18030, etc., in the corefoundation, can find the corresponding code. The Cfnetwork API in the core Foundation is also required to establish a socket connection for the input and output streams. Wait a minute. By setting the nszombieenabled parameter, it is very useful to help resolve memory release errors. When you eliminate an object, if you set delegate for that object, you need to set delegate to nil first, which is a good code habit.
      when you use instruments to detect a memory leak on a 3.0 simulator, you cannot see the function name and only see some address pointers. The simulator in 3.1,3.1.2,3.1.3 are normal, and you can see exactly which function is stored in A memory leak in the. When loading Viewcontroller UI controls through the nib file, the Viewcontroller control can be used in the Viewdidload function. In the Viewcontroller constructor, the control in the nib has not yet completed the link construction. iphone program crashes don't worry. C*****ole and Objc_exception_throw can be used together to quickly locate the root cause. In Cfnetwork, sometimes the Cfwritestreamwrite method is used to write data, which can cause the shelf to be long block.
      cause: When the Cfwritestream cannot accept data, write the data. WORKAROUND: When Cfsritestream receives an asynchronous kcfstreameventcanacceptbytes notification, it begins writing the data. This avoids the case where the cfwritestreamwrite causes the thread to block. Use eavesdrop to crawl network packets.
        There are two simple ways to read image data on the iphone: UIImageJPEGRepresentation and Uiimagepngrepresentation. The UIImageJPEGRepresentation function requires two parameters: a reference to the picture and a compression factor. Instead, uiimagepngrepresentation only requires a picture reference as a parameter. Through the actual use of the process, the comparison found: Uiimagepngrepresentation (uiimage* image) is much larger than the amount of image data returned by uiimagejpegrepresentation (uiimage* image, 1.0). For example, The same picture that reads the same view taken by the camera, Uiimagepngrepresentation () returns a data volume of 199K, while UIImageJPEGRepresentation (uiimage* image, 1.0) The amount of data returned is only 140KB, which is less than 50 KB. If the sharpness of the picture is not required, you can also reduce the amount of the image data by setting the second parameter of the UIImageJPEGRepresentation function. For example, the picture just taken, When reading data by calling UIImageJPEGRepresentation (uiimage* image, 1.0), the returned data size is 140KB, but after changing the compression factor, by calling UIImageJPEGRepresentation ( uiimage* image, 0.5) when reading data, the size of the returned data is only more than 11KB, greatly compressing the amount of data in the image, and from the angle of view, the quality of the picture is not significantly reduced. Therefore, when reading the picture data content, It is recommended to use UIImageJPEGRepresentation first, and set the compression factor according to your actual usage scene, further reduce the size of image data.

Xcode Development Tips--debugging

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.