Guide language: in the current development of the iOS, although the ARC for developers to solve many of the problems of manual memory management era, but memory problems is still producing iOS Crash of one of the main causes, in this paper, the memory, the zombie object, wild Pointers, memory leaks, waste memory that four types of the debugging method and the matters needing attention in your code.

Zombie Objects (Zombie Objects

Zombie object: An object that has been released. In general, accessing or sending a message to a freed object raises an error. Because the block of memory to which the pointer points does not think you have ACCESS or that it cannot execute the message, the kernel throws an exception (EXC) indicating that you cannot ACCESS BAD ACCESS. (EXC_BAD_ACCESS type error)

NSZombieEnabled (enabling zombie mode) is used to solve this problem.

2. Use NSZombieEnabled

NSZombieEnabled provided by Xcode replaces the implementation of Dealloc by generating zombie objects. When the object reference count is 0, the object that needs dealloc is converted to zombie objects. If a message is later sent to the zombie object, an exception is thrown. Select Product -> Scheme -> Edit Scheme -> Diagnostics -> Zombie Objects.

Set NSZombieEnabled. PNG and then in the Product – > Scheme – > Edit Scheme – > the Arguments set up NSZombieEnabled, MallocStackLoggingNoCompact two variables, All values are YES. The following information is displayed:

Set NSZombieEnabled and MallocStackLoggingNoCompact. PNG only set the Zombie Objects, if the Crash occurred in the current call stack, the system can locate breakdown reason to the specific code; But if the Crash is not occurred in the current call stack, a system Crash just let us know the address, so we need to add the variable MallocStackLoggingNoCompact, let Xcode records the history of each address alloc, then through the command return address.

Before Xcode 6, you could also use GDB. You could use the info malloc-history address command to restore the address where the crash occurred to a specific line of code. After Xcode 7, you could only use LLDB and use the bt command to print the call stack. The following is a Crash debugging through zombie mode, using BT to view the effect.

Note: the zombie object detection Settings should be removed before release. Otherwise, every time you access an object through a pointer, you will have to check whether the object pointed to by the pointer is a zombie object, which affects efficiency.

3. Matters needing attention in code

In the ARC era, to avoid accessing freed memory, the code needs to pay attention to the following:

Check code 1: You cannot use assgin or unsafe_unretained to modify a pointer to an OC object

Assgin and unsafe_unretained objects are weak references. If the objects to which the pointer points are released, they become wild Pointers, and a Crash is likely.

Suggestion 1: Assign only modifies OC basic types such as NSInteger and C data types such as short, int, double, and struct, but does not modify object Pointers.

Suggestion 2: The OC object attributes are generally modified with the strong keyword (default).

Tip 3: Use the weak keyword if you need weak references to OC objects, because when the object referenced by the weak pointer is reclaimed, the weak pointer is assigned to nil (null pointer), and there is no problem with sending any message to nil. The use of weak to modify proxy object properties is a good example.

Check code 2: Underlying operations such as Core Foundation

Low-level operations like Core Foundation don’t support ARC and require manual memory management.

Suggestion: Create and release CF objects.

Wild Pointer 1

A wild pointer is a pointer to a deleted object or an area of memory that has not been requested for access. In this case, the wild pointer is mainly caused by the pointer not being null after the object is released. The occurrence of such crashes is relatively random, and it is difficult to find them. A common approach is to improve the recurrence rate of such crashes in the development stage, and to find and solve them as much as possible.

A release message is issued to the OC object, but the memory used by the object can be freed. The system does not immediately reclaim the memory. If other messages are sent to the object at this point, a Crash may occur or there may be no problem. The following figure shows what might happen when accessing wild Pointers (Pointers to deleted objects).

As can be seen from the figure above, the randomness of Crash caused by the wild pointer is relatively large, but when the data randomly filled in is not accessible, Crash must occur. Our idea is: try to fill in inaccessible data to the memory pointed by the wild pointer, and make random Crash become mandatory Crash. 2. Set Malloc Scribble

Xcode provides Malloc Scribble, which can free objects and fill memory with inaccessible data, turning random things into non-random things. Select Product->Scheme->Edit Scheme-> Diagnostics -> Check the Malloc Scribble item. The result is as follows:

PNG Enable Scribble. After the object is allocated memory, 0xAA is added to the allocated memory, and 0x55 is added to the freed memory. If memory is accessed without being initialized or is accessed after being freed, Crash must occur.

Aflatoxin, epoxidized Benzene ratio, General reagent, Drug synthesis reagent,… . Free dissolution. High purity 99.99% to help you. Contact q 2081033207

Note: This method must be connected to Xcode to run the code found, not suitable for use by testers. Based on Fishhook, select the hook object release interface (C’s free function) to achieve the same effect as Enable Scribble. How to locate obJ-C wild pointer random Crash(a) : first improve the wild pointer Crash rate, how to locate OBJ-C wild pointer random Crash(b) : let the non-mandatory Crash become mandatory and how to locate obJ-C wild pointer random Crash(C) : add black technology to make the Crash self-report door

3. Matters needing attention in code

Check for Pointers to OC objects and low-level operations like Core Foundation using assgin or unsafe_unretained modification.

Memory Leak 1

A memory leak is a failure to free up memory that no longer refers to an object. Even though ARC helped us out a lot, there were still a lot of memory leaks; After development is complete, some basic memory leak detection is done.

Memory leak detection, usually using Analyzer (static analysis) + Leaks + MLeaksFinder (third-party tools)

2-1 static Analysis of the Investigation (Analyzer)

Xcode provides Analyzer that analyzes the syntax structure and memory of the code context when the program is not running to find potential errors in the code, such as memory leaks, unused functions and variables. Select Product->Analyze(command+shift+B) to use it.

Analyzer analyzes four main types of problems:

Logic errors: accessing null Pointers or uninitialized variables, etc. Memory management errors, such as memory leaks. Core Foundation does not support ARC declaration error: never used variables; API call error: library and framework not included. After **Analyzer is executed, the common warning types are: **

1) Memory warning

Eg:

  • (UIImage *)clipImageWithRect:(CGRect)rect{

    CGFloat scale = self.scale; CGImageRef clipImageRef = CGImageCreateWithImageInRect(self.CGImage, CGRectMake(rect.origin.x * scale, rect.origin.y * scale, rect.size.width * scale, rect.size.height * scale));

    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(clipImageRef)/scale, CGImageGetHeight(clipImageRef)/scale); UIGraphicsBeginImageContextWithOptions(smallBounds.size, YES, scale); CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(context, 0, smallBounds.size.height); CGContextScaleCTM(context, 1.0, -1.0); CGContextDrawImage(context, CGRectMake(0, 0, smallBounds.size.width, smallBounds.size.height), clipImageRef);

    UIImage* clipImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext(); CGImageRelease(clipImageRef); // Potential leak of an object stored into ‘clipImageRef’ return clipImage; } Analysis: The Analyzer detects memory leaks. The most common ones are CG and CF memory leaks. Another option is to use new delete and malloc free for memory that is not paired with C.

2) Invalid data warning (Dead Store)

Eg:

// Error, Analyzer analysis will tell: Value stored to ‘dataArray’ during its initialization is never read NSMutableArray *dataArray = [[NSMutableArray alloc] init]; dataArray = _otherDataArray;

NSMutableArray *dataArray = nil; dataArray = _otherDataArray; DataArray was initialized to allocate memory, and then assigned to another variable array, causing a data source to request two memory, causing a memory leak.

3) Logic Error monitoring

Eg:

// Error, Analyzer analysis will tell: Property of mutable type ‘NSMutableArray’ has’ copy ‘attribute,an immutable object will be stored instead @ Property (nonatomic, copy) NSMutableArray *dataArr;

// Aflatoxin, epoxidized Benzene ratio, General reagent, drug synthesis reagent,… . // Dissolve for free. High purity 99.99% // to help you. Contact q 2081033207

@property (nonatomic, strong) NSMutableArray *dataArr; NSMutableArray is a mutable data type and should be used to decorate its objects with strong.

Because Analyzer is the compiler according to the code of the judgment, the judgment made may not be accurate, so if you encounter a prompt, should be combined with the code above check; There are also loop references that cause memory leaks that cannot be analyzed by Analyzer.

2-2. Leak tools stored in the investigation

Xcode provides Leak to help find memory leaks in a running program. By selecting Product-> Profile(shortcut command+ I, evoking the Instrument tool interface) -> Leaks. Switch to the Call Tree mode and Separate by Thread, Invert Call Tree, or Hide System Libraries. Finally, click the red button to start “recording”, and the effect is as follows:

On the Leaks debugging interface, 1 is Allocations template, which shows memory Allocations; 2 is the Leaks template, where you can view memory Leaks. If a red X appears, it indicates a memory leak. The main box area shows the leaked objects. Call Tree options are described as follows: Call Tree Option description Separate by Category is classified by type. Expand All Heap Allocations to display Heap memory Allocations between different methods. Separate by Thread is analyzed by Thread. This makes it easier to catch problem threads that are eating resources. In particular, the main thread, which processes and renders all interface data, will stall or stop responding if blocked. Invert Call Tree Invert Call Tree. Displaying the deepest call level at the top makes it easier to find the most time-consuming operations. Hide System Libraries Hide System library files. Filter out the various system calls and display only your own code calls. Flattern Recursion Merge multiple stacks generated by the same recursive function (because the recursive function calls itself) into one MLeaksFinder 2-3, Check (highly recommended)

MLeaksFinder is a third-party tool launched by the wechat Reading team to simplify memory leak detection and is one of the memory leak tools in our current project.

Features: Simple integration, mainly check UI aspects (UIView and UIViewController) leaks.

Principle: Without breaking the development code, hook the POP and dismiss methods of UIViewController and UINavigationController to check that the ViewController object is popped or dismissed for a short time. See if the View of the ViewController object, subviews of the view and so on still exist.

Implementation: Add a method (willDealloc) to the base class NSObject, which uses the weak pointer to point to itself and, after a short interval (3 seconds), checks again to see if the weak pointer is valid. If so, memory leaks.

Integration: It’s easy to import code through Cocoapods or drag it directly into your project. If a memory leak occurs, an alarm box is displayed indicating the location of the memory leak.

Note: For details, see: MLeaksFinder: Accurate iOS Memory leak detection tool and new MLeaksFinder feature

3. Code considerations (Circular references under ARC are the main cause of memory leaks)

Check code 1: Core Foundation, Core Graphics, etc

Operations such as Core Foundation and CoreGraphics do not support ARC and require manual memory management.

Suggestion: Create and release CF and CG objects.

Check code 2: the use of NSTimer/CADisplayLink, because the target of the NSTimer/CADisplayLink object strongly references self, and self strongly references the NSTimer/CADisplayLink object.

Suggestion: Use the extension method, use block or target weak reference target object to break the reserved ring, see iOS Record 8: resolve NSTimer/CADisplayLink circular reference

Check code 3: Block uses code.

Suggestion: Use weakSelf and strongSelf in pairs to break the block loop reference (for blocks without self reference, there is no loop reference, so weakSelf and strongSelf are not needed)

Principle: Define weakSelf outside block, pointing to self object; WeakSelf is captured inside the block to ensure that self is not held by the block; When executing the method inside the block, strongSelf is generated, which points to the object (self object) that weakSelf points to. It actually holds the self object inside the block, but the strongSelf reference only lasts as long as the block executes and is released as soon as the block executes.

Abandoned Memory 1. Overview #####

Abandoned Memory is the Memory of an object that is still being referenced, but can no longer be used in program logic.

You are advised to use Allocation provided by Xcode to troubleshoot such problems. Allocation can track the memory Allocation of applications.

// Lethal // Aflatoxin, epoxidized Benzene ratio, general reagent, drug synthesis reagent,… . // Dissolve for free. High purity 99.99% // to help you. Contact q 2081033207

2. Use Allocation

Xcode provides Allocation because it can track the application’s memory Allocation. Developers repeatedly operate the App to check the memory baseline changes; We can even set Mark Generation to compare memory growth between multiple generations, which is the memory we didn’t free in time. Through Product-> Profile(Command + I, evokes the Instrument tool interface) -> Allocations. Finally, click the red button to start “recording”, and the effect is as follows:

The figure above shows the Statistics Detail Type screen. The following are some names: The Detail column name describes the options for Graph type Category type, or CF object, or OC object, Persistent Bytes Unresolved memory and size Persistent number of unresolved objects Transient Number of freed objects Total Bytes Total number of used memory Total Number of used objects Transient / Total Bytes Freed Memory size/Total Used Memory size Allocation Type Description All Heap & Anonymous All Heap memory and other memory All Heap Allocations All Heap memory All Anonymous The following figure shows the interface for switching to the Call Tree.

PNG Call Tree column Name Description Bytes Used Used memory size Count Total number of symbols Used Symbol Name Description of the Symbol. See instrument-allocations for specific explanations of these nouns

Click on “Mark Generation” at intervals (e.g. 2 minutes) to determine memory growth between generations, which may be memory that has not been released in time: based on the percentage of memory usage, find the portion with the highest percentage of memory usage, and then find our own code to analyze and solve the problem.

PNG is displayed under Mark Generation on the Allocation screen

Aflatoxin, epoxidized Benzene ratio, General reagent, Drug synthesis reagent,… . Free dissolution. High purity 99.99% to help you. Contact Q 2081033207

Omitted, the same as in the memory leak part of the code.

End####

Xcode performs Analyze static analysis using Instruments Allocations to check for memory Leaks that are not timely Accurate iOS memory leak detection tool MLeaksFinder new feature

IOS Crash (part 1)

I am a South China coder, a beginner iOS programmer. IOS real (practice) record series is my little development experience, I hope to throw a brick to introduce jade.

Small gift walk, Jane book attention to me

Applauds support iOS practice record © Copyright by the author All rights Reserved article 96 Concern South China Coder wrote 61403 words, was 1030 people concerned, obtained 951 like iOS app monkey; Web Note AD 1 has been paid by the following topics, found more similar content iOS memory leak programmers iOS &&… Home page submission of articles to read (Pause… Zombie Objects: Objects that have been released. In general, accessing or sending a message to a freed object raises an error. Because the block of memory to which the pointer points does not think you have access or that it cannot execute the message, the kernel throws an exception (EXC) indicating that you cannot access the storage area (BAD ACCE…

Baymax: NetEase iOS App run Crash automatic protection practice Baymax: NetEase iOS App run Crash automatic protection practice Copyright Notice this article is copied from NetEase Hangzhou Front-end Technology Department public account, issued by the author’s authorization. Baymax, a healthy robot in Disney animation Big Hero 6, is a chubby inflatable robot, which is loved by people for its lovely appearance and kind nature, and is called “The God of Meng”. .

IOS crash is a headache for IOS developers, app crash, indicating that there is a problem written code, then how to quickly locate the crash is very important. It’s easier to find the problem during debugging, but it’s more difficult to analyze crash reports for apps that are already live. I used to find a place to change, and rely on others to test and reproduce to find the problem, so that…

Android custom View of various postures 1 Activity display of the viewrotimpl a detailed explanation of the Activity display of the Viewrotimpl … class = ‘class8’ > Window and View…

“Passiontim” reflects on the past year as passiontim passiontim reflects on how hard it has been to find a job and how luck is a part of strength. I’ve been comforting myself with that, but when it comes to the real thing, I feel unlucky. My short trip to Beijing has given me courage. When the door closes, there is always a window. I got a job and did it, even though I wasn’t satisfied. Every day, I muddle around, do not know what to do, do others always dissatisfied, but not…

In the year I was born, a young poet died. They say, there will be no more poetry. What is poetry? Perhaps the earliest poems that every Chinese has memorized are “Geese, geese, geese, singing toward the sky” and “Moonlight shines before my bed and I wonder if there is frost on the ground”… Sketch a small scene, place some emotion or describe beautiful things. Then we memorized “qianshan bird fly off”, “night rain cut spring leek”, “comfortable flower fly light like a dream”… Small…

48 Leng Xiaoxiang legal cost calculator I wish you win the lawsuit ~ modern society legal concept has been greatly popularized, the people solve the problem by relying on violence to turn to the law. In order to maximize the protection of their own rights and interests, enterprises will seek legal protection at the first time when they encounter big problems. However, there are too many laws in the workplace, and when they encounter legal problems, they are often confused and at a loss. If one day your boss is struggling to deal with legal expenses and you log on to a legal fee calculator, 5…

I would like to sigh that some things are really predestined, such as innate talent. Why this person will be a male actor, embark on such a life path, completely can see from its characters, and why will die suddenly in this year. Does his relationship with his wife also have karma? This example is an Adult Film Star eight characters, yichou year, Ding Hai month, renzi day. The sun Lord for the water, hai Zi ugly triad water…

48 Mac Lidbo brand advertisers to start DSP difficult, who fault? In the past 2013, the digital advertising circle is very busy. The new marketing mode represented by RTB and programmatic purchase is exploding the great changes in the digital marketing industry at home and abroad. Its efficient, real-time and accurate advantages are bringing a new blue ocean to marketers. With the emergence of A large number of DSP enterprises, BAT and other giants have entered the programmatic transaction industry chain, the programmatic purchase field shows a vigorous development posture. But…

48 naokou cloud