Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if CGRect null in getter

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.

like image 276
crizzwald Avatar asked Apr 18 '13 16:04

crizzwald


3 Answers

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.

like image 104
rmaddy Avatar answered Oct 16 '22 07:10

rmaddy


Try

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

    return _frame;
}
like image 24
Anupdas Avatar answered Oct 16 '22 07:10

Anupdas


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
like image 22
Andrew DeClerck Avatar answered Oct 16 '22 06:10

Andrew DeClerck