iOS开发 Xcode使用Analyze静态分析

来源:互联网 发布:淘宝买药暗语 编辑:程序博客网 时间:2024/05/15 16:16

一.Analyze简介:

我们可以使用Xcode自带的静态分析工具 Product->Analyze(快捷键command+shift+B)可以找出代码潜在错误,如内存泄露,未使用函数和变量,循环引用等

所谓静态内存分析, 是指在程序没运行的时候, 通过工具对代码直接进行分析
根据代码的上下文的语法结构, 让编译器分析内存情况, 检查是否有内存泄露

二.Analyze主要分析以下几种问题:

  • 1、逻辑错误:访问空指针或未初始化的变量等;
  • 2、内存管理错误:如内存泄漏等; 比如ARC下,内存管理不包括core foundation
  • 3、声明错误:从未使用过的变量;
  • 4、Api调用错误:未包含使用的库和框架。

缺点: 静态内存分析由于是编译器根据代码进行的判断, 做出的判断不一定会准确, 因此如果遇到提示, 应该去结合代码上文检查一下

1.面向用户的文本应该使用本地化(User-facing text should use localized string macro):

解决办法:

在项目中TARGETS -> Build Settings -> Missing Localizability 将Missing Localizability设置成NO

2.从未使用过的变量(Value stored to ‘***’ during its initialization is never read):

解决办法:

把未使用的变量删除

3.instance variable used while 'self' is not set to the result of '[(super or self) init...]

解决办法:

- (instancetype)init{    if (self == [super init]) {        //    }    return self;}

改成:

- (instancetype)init{    if (self = [super init]) {        //    }    return self;}

4.方法返回空(Null is returned from a method that is expected to return a non-null value)

解决办法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    if(tableView == self.selectedContentTableView) {        // make cell...        return cell;    }    else if(tableView == self.recipientTableView) {        // make cell...        return cell;    }    else {        NSLog(@"Some exception message for unexpected tableView");        return nil; // ??? what now instead    }}

改成:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    if(tableView == self.selectedContentTableView) {        // make cell...        return cell;    }    else if(tableView == self.recipientTableView) {        // make cell...        return cell;    }    else {        NSLog(@"Some exception message for unexpected tableView");        abort();  //__attribute__((noreturn))    }}

或者:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    if(tableView == self.selectedContentTableView) {        // make cell...        return cell;    }    else if(tableView == self.recipientTableView) {        // make cell...        return cell;    }    else {        NSLog(@"Some exception message for unexpected tableView");        return [[UITableViewCell alloc] init];    }}

5.The 'viewDidAppear:' instance method in UIViewController subclass '*' is missing a [super viewDidAppear:]call

解决办法:

找到那个UIViewController的方法'viewDidAppear' 加上[super viewDidAppear:animated];

官方文档Xcode执行静态代码分析视频教程

0 0
原创粉丝点击