26

I am trying to check if a CGRect is null in my property getter and if it is, load a value by default, however, in my init method, when I use the property, it returns zero for all values.

Here is my getter:

- (CGRect)frame
{
    if(CGRectIsNull(_frame))
        _frame = CGRectMake(0,0,60,60);
    return _frame;
}

- (id)init
{
    self = [super initWithFrame:self.frame];
    if(self)
    {
        //do something
    }
    return self;
}

I am not sure what's going on and where to look. Any help is much appreciated.

Gabriel.Massana
  • 8,165
  • 6
  • 62
  • 81
crizzwald
  • 1,037
  • 2
  • 14
  • 30

4 Answers4

56

When you create an instance of your class, the _frame instance variable is automatically initialized, even before the init method is called. Since _frame is a C-struct (CGRect), its memory is cleared to all zeroes. This results in a CGRect with all zero values.

CGRectNull is a special, non-zero CGRect. So your check using CGRectIsNull() will never be true.

Using CGRectIsEmpty is a more proper check for this.

Ky -
  • 30,724
  • 51
  • 192
  • 308
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 6
    `CGRectIsEmpty` is the better way to go here, but I think it's worth mentioning that you could also use `CGRectEqualToRect` and compare to `CGRectZero` – Mick MacCallum Apr 18 '13 at 17:03
  • 1
    True but using `CGRectIsEmpty(_frame)` is shorter than `CGRectEqualToRect(_frame, CGRectZero)`. – rmaddy Apr 18 '13 at 17:05
  • It is, and CGRectIsEmpty would be my preference as well, just pointing it out :) – Mick MacCallum Apr 18 '13 at 17:07
  • Thanks, this fixed my issue! I'm new to objective-c and iOS, so learning the libraries and methods that are available to me will come with time. I have pretty strong google-fu, but this one stumped me pretty good. Thanks again! – crizzwald Apr 18 '13 at 19:45
  • @rmaddy sorry about that - just did. – crizzwald Apr 22 '13 at 20:48
12

Try

- (CGRect)frame
{
    if (CGRectIsEmpty(_frame)) 
    _frame = CGRectMake(0,0,60,60);

    return _frame;
}
Anupdas
  • 10,211
  • 2
  • 35
  • 60
2

Here is an updated answer for Swift 4. You are able to simply use CGRect's isNull boolean property to check for CGRectNull now:

let someRect = CGRect.null
print(someRect.isNull) // true
0

Firstly, one needs to understand that a null rectangle and a rectangle which have zero width and height is different.

In Swift 5.0 and above-

To check whether a rectangle is null or not - use the isNull property on the rectangle. Let's say the rectangle variable's identifier is 'myFrame'. Then do following-

if !myFrame.isNull{
    //do sth if the frame is not nul
} 

And for a rectangle of .zero(width = 0, height = 0) frame, check in following way -

if !myFrame.isEmpty{
    // do sth is the frame has height or width
}
Natasha
  • 6,651
  • 3
  • 36
  • 58