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 )
Enabling Analyze During ‘Build’ setting will allow you to start analyzing during compilation.
Localization analysis
The setting Missing Localizability options are updated to Yes in Build settings.
The user-facing text should use string macros. If we directly assign English characters, a compilation warning message will appear, as shown below:
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.
– Auto-completion will allow here to add an initial value to strLength.
– 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.
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.
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: