iOS memory optimization

1, after running MemoryProblems, run crashes EXC_BAD_ACCESS, start NSZombieEnabled, select Edit Scheme and click, Run -> Diagnostics -> Enable Zombie Objects ( dangling pointer detection), after setting up, running again and click on the page, although it will crash again , but this console print useful information, click on the button continue program execution continues to run, compared to the same address to find and modify ( start MallocStackLogging )

Common causes: a variable is assign modification, after the value of the variable, its object is immediately released, and the variable is not strong but weak , still use this time will cause the program to crash


2, manual static analysis: Product-> Analyze or fast the shortcut key shift + command + b for preliminary detection of memory leaks

    Automatic static analysis: Enables Analyze During 'Build' In Build Settings, will automatically compile-time static analysis of each


3, can be opened in the build setting xcode implicit retain of 'self' within blocks, xcode compiler will give a warning, a warning by one investigation


4, Application Leak Instrument for memory leak find: Product menu bar click on the Xcode -> Profile start Instruments, Instruments toolset appears, select Leaks subtools click, click the red dot button to start Leaks tool, start at the same time Leaks tool, simulator or a real machine also followed after boot leaks tool, it will record the program runtime memory allocation information and check for memory leak occurs

First click Leak Checks the time the red cross bar, click on the red cross, shown below Leaks By Backtrace, double-click on a row of memory leaks call stack, the code will jump directly to a memory leak location

Leak Instrument has Cycles & Roots interface: Persistent Bytes and #Persistent. #Persistent is the number of object, that is, the number of allocation, and Persistent Bytes specific memory size. #Persistent is that we need to focus on, there is no memory leak also see this value is not only to rise.

Allocations: Start Allocations, check the list of the top most right setting Check: Discard unrecorded data upon stop, Identify  virtual C ++ objects, * isContain ... Record

Check the list of VM

Generation Analysis

This feature is very useful, generally so used: before entering a page mark it, exit this page again when the mark can compare what it adds, you can analyze which specific memory has not been released


Call Tree: We need to switch the list display type to Call Trees, can very clearly see the call tree

Separate by Category: separated by category, we see the effect on the hook

Separate by Thread: divide according to the thread, I personally do not like this division, because I do not really care about thread

Invert Call Tree: reverse call, we give a comparison chart do not need to explain

Hide System Libraries: This seems to be the will of the hook, because we are only interested in their own way, do not care system

Flatten Recursion: Flat Recursive


Data Mining: Data mining, this is a very functional with a gimmick

Click Symbol, Library will automatically sign you selected row, the library added a small box

Symbols and libraries have two options, whether to filter is diverted; click Restore will remove the selected row small box



5, by looking at whether to invoke dealloc to see if a class leaks

- (void)dealloc

{

    NSLog(@"release XXXXViewController");

}

Method: __weak XXXXViewController * weakSelf = Self ; Block used in the weakSelf


common problem:

1, UITextField in 11 memory leaks iOS: UITextField not release the reasons for using secureTextEntry property solutions

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    if (textField == self.passWordTextField) {

        textField.secureTextEntry = YES;

    }else {

        textField.secureTextEntry = NO;

    }

    return YES;

}


2、使用CGMutablePathRef path = CGPathCreateMutable();时出现Potential leak of an object stored into 'path’解决方案

CGPathRelease(path);

creat,copy作为关键字的函数都是需要释放内存的,注意配对使用。比如:CGColorCreate<-->CGColorRelease


3、The 'viewWillDisappear:' instance method in UIViewController subclass 

XXX is missing a [super viewWillDisappear:] callm,解决方案

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

}


4、调用

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

方法之后在不需要NSTimer时及时调用[self.timer invalidate];千万不要在dealloc方法中调用,因为NSTimer强引用self,所以不会执行dealloc方法。


5、对象之间的循环引用:例子:两个ViewController都需要使用对方,这个时候可以用@class ; 

说明:在 .h 中引入某个类, @class 指的是 当前文件 只是引入类名, 并没有使用类里面的东西. 想要在 .m 里面使用 类的内容的话, 还是要 #import <>, 这种情况跟 上面的对象之间的防止循环引 有点不一样


6、如果是C申请的内存,注意new delete, malloc free的配对处理。


7、图片相关:

缓存:imageNamed:

只需传入文件名.扩展名即可。

可以加载bundle中任意位置的图片,包括main bundle中其他bundle的。

imageNamed方法创建对象的步骤如下:

7.1根据图片文件名在缓存池中查找图片数据,如存在,则创建对象并返回;

7.2如果不存在,则从bundle中加载图片数据,创建对象并返回;

7.3如果相应的图片数据不存在,返回nil。

不缓存:imageWithContentsOfFile:

必须传入图片文件的全名(全路径+文件名)

无法加载Images.xcassets中的图片。

对于大的图片且偶尔需要显示的应放到工程目录下,不要放到Assets.xcassets中;并使用imageWithContentsOfFile加载不让系统缓存

background.image = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/*.png"]];

对于经常需要展示的小图片放到Assets.xcassets中让系统缓存,使用imageNamed加载

background.image = [UIImage imageNamed:@"*.png"];


不常用大图:将imageView.image = [UIImage imageNamed:nameArr[index]];

改为imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:nameArr[index] ofType:@"png"]];


8、出现VM:CG raster data,SDWebImage的问题

需要在Appdelegate中设置一下

[[SDImageCache sharedImageCache] setShouldDecompressImages:NO];

[[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:NO];

[[SDImageCache sharedImageCache] setShouldCacheImagesInMemory:NO];


9、VM:CoreAnimation

Found out that animation caused by the inner pages.

Inside the pageViewController(viewController that added to the scrollView as a page) on viewWillDisappear:(BOOL)animated method I added this

for (CALayer* layer in [self.view.layer sublayers]) {

        [layer removeAllAnimations];

}

it resolved the problem.


10、@property (readwrite, nonatomic, copy) NSMutableURLRequest *request;出现Property of mutable type 'NSMutableURLRequest' has 'copy' attribute; an immutable object will be stored instead,解决方案

@property (readwrite, nonatomic, strong) NSMutableURLRequest *request;


Guess you like

Origin blog.csdn.net/u013069892/article/details/80495272