0

Guys can somebody explain me what the if (! origin) means please!

-(void) setOrigin: (XYPoint *) pt {
        if (! origin)
        origin = [[XYPoint alloc] init];
        origin.x = pt.x; origin.y = pt.y;
        }
1
  • Did you look in the language documentation?
    – Jerry101
    Feb 8, 2015 at 18:22

2 Answers 2

0

The posted code reads funny. Externally, the method appears to promise to set some object's origin property to the value of a passed point (pt). Internally it appears to only do so if the origin property is not already set.

Regarding the '!' bang or not operator, at the lowest level, ! tests for non-zero. When applied to a boolean, like YES or NO which are really scalars 1 or 0 it acts as a logical NOT operation...

!YES is the same as !1 and equals NO
!NO is the same as !0 and equals YES

In the code in the question, ! is applied idiomatically to a non-scalar value, to an object pointer, but its doing the same thing at the low-level, testing for non-zero-ness, in this case non-nil:

SomeObject *someObject = nil;

!someObject is the same as !nil and the same as !0 and equals YES

If the object has been allocated, the pointer someObject has a non-zero value, so

SomeObject *someObject = [SomeObject alloc];

!someObject equals NO

A common use for this idiom is the lazy getter. Properties are initially nil, and then given non-nil values the first time they are requested.

- (NSString *)someStringProperty {
    if (!_someStringProperty) {
        // this runs the first time, but not again because we set
        // _someStringProperty to be non-nil here
        _someStringProperty = @"hello world";
    }
    return _someStringProperty;
}
0

If there is no origin. '!' in an if statement mean if this is not true.

What your code does, is it checks if there is an origin, if there isn't it will create a new one. The reason why its good to do that is because you don't want to make more than one origin.

Hope this helps. If you have any more questions, feel free to ask. :)

Not the answer you're looking for? Browse other questions tagged or ask your own question.