Post

Xcode Static Analysis

Static Analysis

Xcode provides a static analysis tool that can detect potential problems such as localized text, logical problems, memory problems, issues, and data syntax problems, etc.

To perform static code analysis: Select -> Product > Analyze ( command + shift + B )

Screenshot-2020-09-29-at-11.29.17-PM-179x300

Enabling Analyze During ‘Build’ setting will allow you to start analyzing during compilation.

Screenshot-2020-09-29-at-11.40.25-PM-768x261

Localization analysis

The setting Missing Localizability options are updated to Yes in Build settings.

Screenshot-2020-09-29-at-11.53.37-PM-768x186

The user-facing text should use string macros. If we directly assign English characters, a compilation warning message will appear, as shown below:

Screenshot-2020-09-30-at-1.55.50-PM-768x366

Logical analysis

Logic analysis of potential logic problems in static analysis code, such as accessing null pointers, uninitialized variables, or initializing zero-length arrays, etc., as shown in the following figures:

– If you try to remove an element from the array arrSample it will crash.

Screenshot-2020-09-30-at-2.02.44-PM-768x287

– Auto-completion will allow here to add an initial value to strLength.

Screenshot-2020-09-30-at-2.08.26-PM-768x261

Note: A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions.

Screenshot-2020-09-30-at-2.11.25-PM-768x267

Memory analysis

Memory management errors include memory leaks etc.

  • core foundation is not included under ARC memory management, you can use __bridge_transfer or CFBridgingRelease to move the ownership of the Core Foundation object to the under the Objective-C ARC object ownership. refer [Medium Article].
  • ARC is responsible for relinquishing ownership of the object.

Note:

  • The compiler does not automatically manage the lifetimes of Core Foundation objects; you must call CFRetain and CFRelease.
  • Creating an object to request memory but not using it causes memory leaks.

Screenshot-2020-09-30-at-2.21.34-PM-768x324

Static Analysis Tools

  • OCLint – OCLint is a static code analysis tool for improving quality and reducing defects by inspecting C, C++, and Objective-C code.
  • SwiftLint – A tool to enforce Swift style and conventions.
  • Sonarqube – A paid tool that supports more than 15 languages, includes Swift and Objective-C.

References:

This post is licensed under CC BY 4.0 by the author.