In Objective-c what is the difference between @YES/@NO and YES/NO? What types are used for each?
What is the difference between @YES/@NO and YES/NO?
9.5k Views Asked by cdub AtThere are 3 best solutions below
On
The difference is that by using @ you are creating an NSNumber instance, thus an object. Yes and No are simply primitive Boolean values not objects.
The @ is a literal a sort of shortcut to create an object you have it also in strings @"something", dictionaries @{"key": object}, arrays: @[object,...] and numbers: @0,@1...@345 or expressions @(3*2).
Is important to understand that when you have an object such as NSNumber you can't do basic math operations (in obj-c) such as add or multiply, first you need to go back to the primitive value using methods like: -integerValue, -boolValue, -floatValue etc.
You probably seen it because foundation collection types works only with objects, so if you need to put a series of bools inside an NSArray, you must convert it into object.
@YESis a short form of[NSNumber numberWithBool:YES]&
@NOis a short form of[NSNumber numberWithBool:NO]and if we write
the above if statement will execute since the above statement will be
and it's not equal to
nilso it will betrueand thus will pass.Whereas
YESandNOare simplyBOOL'sand they are defined as-YES&NOis same astrue&false,1&0respectively and you can use1&0instead ofYES&NO, but as far as readability is concernedYES&NOwill(should) be definitely preferred.