Reputation: 1907
Is there a way I can get a warning when I'm assigning a variable instead of checking equality? There have been many times where I have accidentally assigned, rather than compared, and it would be great to have a warning!
Is there a way Xcode can warn me without having to change coding styles to:
if (YES == aVariable) {...}
Upvotes: 3
Views: 3798
Reputation: 2616
The compiler flag Wparentheses
should do the trick. It will force you to place parentheses around assignments in a conditional in order to compile. Clang has this flag set by default.
Upvotes: 1
Reputation: 385540
Xcode already warns you if you use =
instead of ==
in an if
statement in most cases. If you're not getting the warning, tell us what version of Xcode you're using, how old your project is, and what build settings you have changed from their defaults.
My test: I created a brand new iOS app in Xcode 4.5.2 and didn't change any build settings. I just added a little code to application:didFinishLaunchingWithOptions:
to trigger the warning. Here it is:
You can disable the warning by setting the compiler's -Wno-parentheses
flag (but why would you want to?). You can suppress the warning in a particular case by adding an extra set of parentheses around the assignment:
if ((x = 7)) {
There are two cases where you don't get the warning by default. First, in an init
method, you can assign to self
, like this:
- (id)init {
if (self = [super init]) { // no warning by default
...
Second, in any context, you can assign the result of the nextObject
selector, like this:
while (object = [enumerator nextObject]) { // no warning by default
You can enable warnings in these cases by setting the compiler's -Widiomatic-parentheses
flag.
Upvotes: 10