What is the difference between @YES/@NO and YES/NO?
Asked Answered
D

3

29

In Objective-c what is the difference between @YES/@NO and YES/NO? What types are used for each?

Danita answered 3/6, 2015 at 5:38 Comment(0)
E
46

@YES is a short form of [NSNumber numberWithBool:YES]

&

@NO is a short form of [NSNumber numberWithBool:NO]

and if we write

if(@NO)
   some statement;

the above if statement will execute since the above statement will be

if([NSNumber numberWithBool:NO] != nil)

and it's not equal to nil so it will be true and thus will pass.

Whereas YES and NO are simply BOOL's and they are defined as-

#define YES             (BOOL)1

#define NO              (BOOL)0

YES & NO is same as true & false, 1 & 0 respectively and you can use 1 & 0 instead of YES & NO, but as far as readability is concerned YES & NO will(should) be definitely preferred.

Endorsement answered 3/6, 2015 at 5:49 Comment(3)
I got your point, but I tried BOOL status = @YES; which worked for me without any warning or error.Shotputter
@Exploring, BOOL a = 1.0;, BOOL aa = self; BOOL aaa = @"abc"; all these statements will also work, without any complains from the compilerEndorsement
They will, because an assignment to a BOOL by definition of the language checks whether the assigned item is non-zero or non-nil and assigns YES or NO.Barahona
A
19

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.

Allyl answered 3/6, 2015 at 5:45 Comment(2)
This is a better answer than the currently accepted answer.Vigilant
@KPM, yes I agree, it is better.Endorsement
C
4
  1. @YES/@NO is type of NSNumber,is used when do something with Foundation object.For example

    NSMutableArray * array = [[NSMutableArray alloc] init];
    [array addObject:@YES];//true
    [array addObject:YES];//Wrong
    
  2. YES/NO is BOOLs

Centurion answered 3/6, 2015 at 5:47 Comment(1)
YES and NO are BOOLs, not Booleans.Kiddush

© 2022 - 2024 — McMap. All rights reserved.