Variable assigned to itself
ID |
objectivec.correctness.self_assignment |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Suspicious Code |
Language |
Objective-C |
Description
Reports an assignment whose left and right sides are the same expression - a bare name, a one-level property access (self.title = self.title) or a one-level instance-variable access through →. Deeper chains such as a.b.c = a.b.c are not reported, and neither is self.name = name, where the two sides name different things. Comparisons and compound assignments are not assignments of this shape and are not reported, and neither are occurrences inside a comment or a string literal.
Rationale
Assigning a variable to itself has no effect, so the statement is either dead or a typo for the statement that was meant - most often the wrong side of a copy, where a parameter should have been stored into an instance variable and the two names happen to be spelled the same. In an initialiser or a setter that means the value the caller passed is quietly discarded and the object keeps whatever it already held. The compiler accepts it, so nothing points at the line until the field turns out to be empty.
The following code illustrates the pattern detected by this rule:
@implementation Assignments
- (void)copyInto:(NSInteger)count title:(NSString *)title {
// FLAGGED: Variable assigned to itself
count = count;
// FLAGGED: Variable assigned to itself
self.title = self.title;
// FLAGGED: Variable assigned to itself
_name = _name;
// FLAGGED: Variable assigned to itself
self->_slot = self->_slot;
NSLog(@"%ld %@", (long)count, title);
}
@end