Is (obj && obj! = Nil) right and necessary?

Two parts of this question

1) Is this an understanding of what is going on right?
"if (obj)" checks if the pointer 0x0 is specified, aka set to the integer memory address
"if (obj! = nil)" compares the memory address of the object with the memory address of the universal object nil

2) Therefore, in a situation where I do not know if a variable is pointing to something, and if so, I also do not know whether this object is a valid object or zero. I want to do many things based on this information, and not just pass on the obj message, which, as I understand it, would be safe if it were null. Is this code correct and necessary?

if (obj && obj != nil) {
    // Do a bunch of things that should only happen if obj is pointing to a valid object
    [obj someMessage];
    [anotherObj someOtherMessage];
}

Thanks guys!

+3
source share
5 answers

Correctly? Yes. Is it necessary? No Objective-C is simply #define nilup to (void *)0what is false in C terms. Therefore just write

if (obj) {
    [obj someMessage];
    [anotherObj someOtherMessage];
}

. Also, since Objective-C has a message nil, you can simply omit validation in some cases. (For example, if the second line was not in a block if, you can simply call [obj someMessage]indiscriminately.)

+17
source

This is correct, in the sense that it will give you the result that you expect, but superfluous. Simple enough to use:

if (obj) {

or

if (obj != nil) {
+12
source

if (obj). objc.h, nil #define __DARWIN_NULL. /usr/include/sys/_types.h, , __DARWIN_NULL 0L, 0 (void *)0, , C ++. , nil false, if (obj).

+4

, , 2: , " ", , , , , , , " " . , :

  • , .
  • , ,
  • int,
  • C, NSString

, . , , .

+4
source

if (obj == nil), then if (obj) will evaluate to false. You do not need both.

0
source

Source: https://habr.com/ru/post/1723274/


All Articles