Mutable file-scope static variable

ID

objectivec.maintainability.avoid_private_static_members

Severity

info

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

medium

Resource

Mutable State

Language

Objective-C

Description

Reports a mutable static variable declared at file scope in an implementation file. A declaration carrying const is the recommended form and is not reported, in either spelling; a static function is not a variable and is not reported; and a static declared inside a method - the dispatch_once singleton idiom - is a different construct and is out of scope, which the rule enforces by requiring the declaration to start in the first column.

Rationale

A file-scope static is shared, hidden state. Every method in the file can write it, nothing outside the file can see that it exists, and its lifetime is the process rather than any object - so two instances of the class that appear independent are not, and a test that ran earlier leaves the value it wrote behind for the next one. It also has no synchronisation of its own: a static touched from more than one queue is a data race that the type system will not point at.

The following code illustrates the pattern detected by this rule:

// FLAGGED: Mutable file-scope static variable
static NSInteger sRequestCount;

Remediation

Make the state belong to something. An ivar or a property moves it onto the instance that owns it; a class property or a value passed in as a parameter makes the dependency visible at the call site. Where the value really is process-wide, put it on a singleton whose lifetime is explicit, and guard it with a queue or a lock. If it never changes, declare it static const - that is the form this rule deliberately allows.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved