How to debug your iOS program

Source: Internet
Author: User

iOS various debugging Tips Deluxe Package Normal operation

3

The basic breakpoint operation is as follows

Figure 4

Click on the Black column to create a breakpoint, click again to temporarily cancel the breakpoint (but do not delete), long press the breakpoint dragged out of the delete (Mac OS system Engineer is the pleasure of the drag of rice porridge), of course, you can right-click on the created breakpoint, will pop up the corresponding menu.
Of course, you can also monitor a variable!
Figure 5

In the object view, right-click an object and tap "Watch ' xxx" to complete the monitoring of the XXX object.

Here I monitor the lab's Uilabel variable, and whenever that variable is updated its information is printed to the console.
All right! We have learned the basics of creating breakpoints, where is Xcode comfortable? is the debug mode and run mode, can be said to be seamless switch, you just do not create a breakpoint, then is the normal mode of run, if you create a breakpoint and run to break point, it will automatically enter the debug mode, unlike an EC at the beginning of the IDE, the control panel is like flying aircraft, Tens of thousands of buttons are very powerful, in fact, only with the run and stop, what is the debug mode, App mode ..., and indeed the superiority of xcode in contrast more intense, comfortable to the extreme, just like summer wind blowing chrysanthemum, ah yes is that feeling!
We create a breakpoint, and it automatically stops as it goes, like this:
Figure 6

The most basic operational skills of these debugs are for every beginner iOS developer to master, should be as an instinct, like a dog likes to eat Xiang (oh sorry bo is not discriminatory dog meaning, Bo Master also raised dog, very two but never eat Xiang! Really as far as I know it never eats xiang, here is just a metaphor metaphor).

Global Breakpoint (Globals breakpoint)

Sometimes in the case of error in the program can not accurately locate the line of code, but directly into the main loop or appdelegate inside, or will give you such a hint:

EXEC_BAD_ACCESS:

Is there a kind of impulse to cry? At least give me some information about the stack. This time you must not hit the mouse and keyboard Oh, everything is the host in operation, you hit the mouse and keyboard what is the use? Should be kicked host AH ~ ~, now has a global breakpoint, mother no longer worry about you hit the mouse, you only need this:
Figure 7

In the debug navigation panel, you set up a global breakpoint, so that whenever you encounter an error, the debug program will automatically locate the information on the bottom of the stack, which is the line of code that you first went wrong, so you can have a happy debug pull ~ ~

Conditional breakpoint (condational breakpoints)


Once upon a time there was a game called the roll, some players they know how to operate, will put the skills will walk, but they do not know to buy equipment, play a game down, shoe knives are not bought. Why do I tell this story? Because many children learn things and play games, read the previous several debugging skills, think that they have been the cock invincible, in fact, they are just out of the game without equipment players, if only the use of the above debugging skills can only be said to be low play, in the high-quality chicken before it will be instantaneous seconds of the kind, So learn to equip themselves is the King! Conditional breakpoints, is learning to target!

Let's take a look at the code
Figure 8

Do you want to ask bloggers why they are so coquettish, unexpectedly on the swift!! I just want to sing a wet now: Others laugh at me too lewd, my family lives in the yellow Crane Tower.
Anyway, everyone in this era is full of support, Bo Master is also, so learn swift.
If we use a breakpoint in a loop, if the loop executes 1 million times, then your breakpoint will be executed so many times, don't you think the egg is cold sadness? So we do this:
Figure 9

This will only be triggered when the breakpoint is traversed to c== "H".

Figure 10

Isn't it great?
Some children's shoes titanium alloy dog eyes have seen the edit breakpoint there is something on the action, what is it?
This is very powerful, can be in the position of your breakpoint, perform various operations, such as executing script commands, console commands (can make debug information custom save), printing information, etc.
Bo's favorite is this log message, simple rough! There is no need for print AH nslog, directly on the breakpoint action printing (in fact, this is a combination of Xcode and debugger high-energy products, described below). Specifically, this can be:
Figure 11

Actually just Bo Master lied, Bo Master favorite action is not log Message, but sound, as the name implies, the breakpoint shot on the bug, so that the breakpoint will be issued sound, hear my own set of voice, I know what is the bug, hearing the bug, Oh, exec_ Bad_access error I set into the voice of Mr. Hatano, unrecognized selector send to INSTANCD error I set into the teacher's ... Do not ask me how the system does not Akiho Yoshizawa the sound of step, I do not know who is Akiho Yoshizawa step.

And, of course, more powerful conditional breakpoints are the goods.
Figure 12

After adding, enter Viewdidload in the Symbol field.
This will trigger a breakpoint when all viewdidload methods in the program are called.
Figure 13


Of course, we can also add breakpoints just for a particular class of methods. Enter [ClassName Viewdidload] (objective-c) or Classname.viewdidload (Swift) in the Symbol column.
For example: Unrecognized selector sent to instance 0xaxxxx This error, this instance can quickly locate
Figure 14

The Art of printing

Although Arc has made memory management simple, time-saving, and efficient, it is still important to keep track of important events in the Life-cycles of object. After all, arc does not completely exclude the possibility of a memory leak, or attempts to access a release object. For this purpose, we can be very artistic to spy on what the object is doing, and think about it is good to have pleasure.

NSLog

Small partners in the first class to learn the life cycle of Viewcontroller, the teacher must be very wretched to teach you, in Viewcontroller each life cycle of the method used NSLog to peeping! Yes, this is actually the simplest way to trace the life cycle of the explosion, but the system's own nslog is a bit weak, the output of too little information, simply can not meet our desires, here I teach you to strengthen your log!!
You can use the following macro

//A better version of NSLog#define NSLog(format, ...) do { fprintf(stderr, "<%s : %d> %s\n", [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, __func__); (NSLog)((format), ##__VA_ARGS__); fprintf(stderr, "-------\n"); } while (0)

About the power of macros people can get into my blog. Preliminary study on pre-compiling instructions in iOS
That's what you print (in fact, NSLog's print is very inefficient, even 100 times times lower than print, and interested in flipping the Apple Handbook).
When using OBJC language (strong type) and printing with NSLog, it is often unclear nslog (@ "%", xxx) xxx What type of output should be%d or%@ or%f???? Silly points not clear ~, so play turn nslog you should know the following these global methods!
Figure 17

Turn on Zombie object (enable Nszombie Objects)

Xcode can turn objects that have been dropped to "zombies", and when we visit a zombie object, Xcode can tell us that the object being accessed is an object that should not exist. Because Xcode knows what this object is, it allows us to know where the object is and when it happened.
So zombies is your good base friend! He can let you output the information more specific!!
Specifically, do this:
Figure 15


Try to output the information of object again, isn't it great?
Zombies can only be used in simulator and OC language Oh ~

Attack on the Yards farm

If you have printed the art of using the wind and the use of breakpoints can be arbitrary, then you have been in the confrontation with the forced chicken, stable most of the winning, you have been a Pride cool programmer, overlooking all the low-energy of the Force excellent chicken! But! Face a more powerful enemy--your bald, 1000°, short-sighted tooth with leek in front of a colleague who has 10 years of fighting with the chicken, and nasty eyes with eye-poop but can kill your interviewer with eyes ... For them, you are still too weak, your skills are honed too little! So you have to attack!! Even more powerful enemies than the chickens are coming! We need more powerful weapons.

Console (LLDB command)

Our goal is to be armed to the nose hair! Console window Everyone knows which black many words will come out, especially when the chicken to be forced to dry, then the students have encountered this console it
Figure 16


The compiler history of our family Please enter the preliminary inquiry of pre-compiling instructions in iOS, yes we are now using the world's best C, C + +, OC, Swift compiler--LLVM,LLDB is the best LLVM debugger in the world! Don't be shy, because we are the best! So be sure to use the best! Please do not hesitate to use, just like their own home ah, ah haha eat not only to eat, multi-clip dishes ... Hey ~ Bo The host of the hospitable occupational disease again committed ~, what? You don't know where to use LLDB?
First of all! You'll have to crash or break the program! Until you see the word (LLDB) in Figure 16, you can hit the command.
Every time you want to view variables, constants, you want to re-write nslog to print, then recompile, go to execute, start again? Too tired to have lldb you just do it
Figure 18

Isn't it convenient to explode?
When you have a switch statement, you want to test every case, you have to create false conditions to test; there is a if...else ... statement, you want to test different situations, you have to hard code to write a different situation, compiled several times in order to test each case ..., I think you should know why your hair is so sparse.
In these cases, just one compilation, using the LLDB thread command, fake return value, cheat register, you can do all the tests as you like.
Isn't it a blast?
Lldb really strong, Bo Master did not deceive you, this blog to this all debugging skills LLDB can be implemented, a variety of breakpoints, various printing, call Python plug-ins, run interrupts, operating hardware underlying, control program running threads ... lldb can do it! As if LLDB is another powerful world!!!
Isn't it powerful to explode?
In fact, if you do not want to can chew, you just proficient in this debugging tool, basic debugging skills in front of you can not learn, in here Bo Master is also no, LLDB's strong not Bo master casually say a few words can express out of,
More need everybody hands, can truly appreciate that kind of beautiful, that kind of carefree and incomparable debugging experience!
Here Bo Master selflessly took out any door, here is a very good article! Can let you have a good aftertaste, hehe
"The Lldb Debugger"
"About Lldb and Xcode"
A tentative study of the LLDB Commissioning command
"Dance with the debugger-Lldb's Waltz"

Profile (instruments)

Figure 19


How does this thing translate? Let's call it an Inspector!! Maybe you've been learning iOS for half a year, and you've never noticed or used this tool, but bloggers are responsible for telling you that any great app on the market will use instruments to make the code more robust! is instrument an aphrodisiac? How does it make code robust?
This sturdy is not that strong ~ ~ ~ ~ I am only 18 years old can be pure a little

Instrument contains a lot of tools, memory overflow analysis, performance analysis, various analysis ... If in detail, this can really open a blog for each tool, but the blogger is a person who knows how to give people to fish as the truth of the old driver! So the blogger certainly won't say it all again! Let's take a look at the use of dedicated debug memory overflow analysis tools!
Figure 20


You can try this "Analyze" before you use leaks.
Figure 21


Analyze can quickly discover the problem of release in your code, as well as the lack of a parent method in the inheritance process, and so on! Generally a good iOS development engineer No Warning, Pass analyze is the most basic conduct! I know you've been numb to hundreds of warning on your own projects, but bloggers, I'm in charge of telling you, this is not good! , because there is a Yunnan folk song "Old Driver Bring Me" listen to the Bo Lord refreshed!

Stick to your virginity as an iOS developer! Follow me shouting slogans!

No warning! Pass analyze!

We'll keep coming back. Use leaks! If the analyze are passed, then you can use the leaks tool to discover the old age demon level of the side leak!
Figure 22


If you are prompted for an object with a risk of a side leak, you can also eject the side extension details like this
Figure 23


Direct click on the method can be directly into the code section!!
Isn't it very simple and rude! Of course there are many other tools, but what is called space is always limited to people, ah, real egg pain ~ Really want to say a little more
Want to know more about instrument you can read this article!
"How to use Instruments in Xcode"

Xcode View Debugging

Sometimes some forced chicken hidden deep, the code almost turned over, or did not find out where the problem, Bo Master can understand that the wind messy, the bright of the egg, because countless day and night Bo Master is deep in the can not extricate themselves, and then simply re-create a project directly! Or not!! I go, until one day the Bo master in the morning, see the mirror of their handsome face, I suddenly epiphany, the original handsome can be so fast to find bug! The ultimate lock is cute and hateful xib and storyboard out of the question!! A constraint or view nested logic or team collaboration git conflict and so on, causing io-v what's wrong, this situation to check the view file, may Xcode crash can not open the Xib or storyboard, You directly use the Text tool to open this XML type of markup file, you almost spit blood, tens of thousands of rows of records dog eyes are blind ....

But this history is coming to an end!! Because of our powerful Xcode view debugging Function!!

The following content, complete copy, if there is discomfort, insist on reading! Please call me a happy Porter!
Copied from "View Debugging in Xcode 6"
Apple has made a lot of obvious improvements and optimizations in Xcode 6, and view debugging is one of them. In general, the app user interface does not behave as expected by the developer, such as not showing the view, or not showing it correctly. This article explains how to use Xcode's new view debugging feature to simplify the developer's validation and repair of the problem interface.

1.Demo Engineering

Start by downloading the sample project from GitHub (https://github.com/tutsplus/ViewDebugging) and opening the viewdebugging.xcodeproj. The project contains a simple clickable application with a handful of view controllers, an application delegate, and a storyboard. The app is designed for the iphone but benefits from the adaptive layout of iOS 8, so the interface is no problem on any device.

The application sample project that you just downloaded is a simple to-do list application that contains a simple screen that can see additional information, such as the number of items in the sample project, the avatar of the user, and the Twitter action of the @***. Clicking the Run button in the upper left corner of Xcode will show the app running in the iOS emulator.
Figure 24


You will soon notice that there is a problem in the user interface-no data is displayed in the table view. Open Firstviewcontroller.swift in the Project navigation panel and locate the following code:

var mockNotesDataSource: [String] = ["Do some laundry", "Finish homework", "Walk the dog", "Learn about view debugging"]{didSet{self.tableView.reloadData()}}

You can see that the Mocknotesdatasource variable is the data source for the table view. Using the Swift Property Viewer feature, the table view is automatically reloaded when the data source changes. By looking at the code snippet above, you'll see that there should be 4 items in the app that need to be shown, but not showing the data right now means there's something wrong in some places.

Enable View debugging

The problem seems to be related to the user interface. While running the app, press the Debug View Hierarchy button at the bottom or choose Debug > View debugging > Capture View Hierarchy from the menu to start the View debugging.

Figure 25


After you start the view debugging, Xcode will take a snapshot of the application's view hierarchy and present a three-dimensional prototype view to explore the level of the user interface. In addition to showing the app's view hierarchy, the three-dimensional view shows the location, order, and view dimensions of each view, as well as how the views interact.

The three-dimensional view of the example project in Xcode is normal, but the table view cells seem a bit too wide.
Figure 26


Pause application debugging and select Main.storyboard on the left to fix the problem. Click on the table view and select Editor > Resolve Auto Layout issues > Reset to suggested Constraints.
Figure 27


Compile and run the application again to determine that the user interface is displayed correctly. Click the Debug View Hierarchy button to learn more about the functionality of view debugging.

View Debugging Features

Click and drag on either side of the three-dimensional rendering diagram to rotate or tilt the user interface, tilt left or right to select a table view.

When selected, Xcode highlights the view and displays the object and size inspector on the right. Check the top of the jump bar and confirm that UITableView is the last item on the right.
Figure 28

The Object and size inspector includes a lot of useful information. In the past, developers needed to rely on log statements or breakpoints to check the configuration of views.

Open the Size inspector (spec inspector) on the right and the auto Layout below to see that the correct constraints have been applied to the view. In Object inspector, we can examine the properties of the selected view.
Figure 29

In the debug area of Xcode there are 9 buttons and sliders to be used during debugging.
Figure 30


Sort from left to right controls:

Adjust view spacing: Adjusts the spacing between different views.

Show what is clipped: the part that is clipped in the current display view.

Show constraints: Show constraints on the selected view.

Reset viewing area: Restores the rendered perspective to its default state.

Adjust viewing mode: Selectively display 3D rendering perspectives, such as displaying only content, showing frames, and displaying content and frames at the same time.

Zoom out: Zoom out 3D Rendering perspective

Restore: Restores the rendered perspective to the default size.

Zoom in: Enlarge 3D Rendering Perspective

Adjust the visual view range: Hide or Show views, step-by-step resolution of the 3D rendering view, slide the slider left or right to the opposite effect.

It is recommended to take a little time to get started with these spaces and to understand their usefulness.

View Layer Sorting

Compile and run the application again, and click the "More" tab at the bottom of the user interface. The first glance to the interface looks OK, but it does not follow the developer's definition of accurate execution, the image of the blur effect is not shown. We can better determine where the problem is by debugging the view hierarchy.

Drag the view to the left or right to see the situation, then drag the View Spacing slider to the right.
Figure 31


As a result, the spacing between the different views becomes larger and the levels clearer, and we see another view hidden in the picture "below", with the hidden view, which is the "lost" visual view.
Figure 32


Open Main.storyboard and select Second View Controller Scene. In the document Overview panel on the left, expand the View object of the second view Controller to see the sorting of the child views.

Xcode stacks The view in ascending order in the document overview, in other words, the top-level view of the list is the basis of the view hierarchy.

Fixing the problem is simple. At run time, Blur Effect view is hidden under sky image because it is the first view in the view hierarchy. Click and drag Blur Effect View in the document overview and the results will be as shown:
Figure 33


Run the application again to see the blur effect. The user interface of the application appears to fit the design's purpose. We can also look at other debugging features of the iOS emulator to see what other places or features have been perfected.

5.iOS Simulator Debug function

Compile and run the application, check the emulator, and choose the color blended layers option from the Debug menu.
Figure 34


You will then see that the app's user interface is covered in red and green, showing which layers can be overlaid and which layers are transparent. The blending layer is a computationally intensive view, so it is recommended to use opaque layers whenever possible.
Figure 35


Apple notes this in its documentation (IOS Simulator User Guide) and uses opaque layers on table view processing. There are some things that are not good when scrolling through the view, one important reason is that you use a blend layer, and if the content background is opaque, the page scrolling effect is smooth and smooth.

For this application, there may be inconsistent scrolling performance if the user has hundreds of items to show. The table view cell is currently using a blend layer. Because the view controller's view background is white, the end user will not be aware of the difference, regardless of whether the table view cell is using a mixed layer or an opaque layer.

Open Main.storyboard and select the Table View cell property in the To Do list scene. In the property inspector (Attributes Inspector), scroll down the drawing partition and select Opaque.
Figure 36


Compile and run the application in a state where color blended layers is enabled. Because table view cells now use an opaque layer, they are covered with green to indicate that they are opaque.

In addition to tagging layers, there are other useful features to help developers debug apps in the iOS simulator. Here are some of the more useful:

Toggle Slow animations in frontmost app: Check the simulator to open the Debug menu to select the Toggle Slow animations in frontmost app, which reduces the speed of animations in the app and is suitable for debugging Applications that contain complex animations. Also use the shortcut key command-t to operate.
Color Copied Images: This option adds a blue-green overlay to a picture that was copied by the core animation when it was drawn.
Color misaligned Images: If the picture boundary is not perfectly aligned with the target pixel, this feature will overlay the picture with a magenta color. If the picture is drawn with a determined scale size, the feature adds a yellow overlay to the picture.
Color off Screen Rendered:. This option adds a yellow overlay to the off render content.
Many developers ignore the design problem of applying the status bar when accessing the phone, and you can simply test by triggering the status bar in the call. In the iOS emulator, from the Hardware menu, select Toggle In-call Status Bar.

To see how the app responds to events, press COMMAND-T to enable slow animations and press Command-y to show the status bar when the phone is plugged in. If your app uses a navigation bar, the operating system will take care of it for you.
Figure 37


In addition to coloring the view, remember that the iOS emulator can also debug the core location issue. You can simulate a device in a specific latitude and longitude,

If your application uses icloud to manage data, you can also trigger synchronization events manually.

The demo app used in this article is very simple, and using the technology mentioned here will save you a lot of time in the future. View debugging can help you fix many of the problems that occur in the user interface.

In addition to Xcode and Interfacebuilder, using the iOS simulator's debugging capabilities can improve application performance and identify bottlenecks in the development process. Apple's human-Computer Interaction Guide (English version) emphasizes the importance of a positive response to the app, which makes the user feel that the app is easy to use and operate. Apple's ascent to Interfacebuilder has made view debugging easier than ever.

How to debug your iOS program

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.