objective-c - world - objective c vs swift




How do I check if a CGPoint has been initialised? (4)

I would like to initially set a CGPoint property to a particular point (middle of screen). Other methods may subsequently wish to change this property. My thoughts were to initialise it if empty in the getter, but I get the message invalid argument type 'struct CGPoint' to unary expression. I also tried using if property == nil or 0 but no joy.

Any thoughts?

-(CGPoint)graphOrigin
{
    // initialise to centre of screen if has not been set
    if(!_graphOrigin) // this expression is causing the problem
    {
        CGPoint origin = CGPointMake(self.bounds.origin.x + self.bounds.size.width / 2, self.bounds.origin.y + self.bounds.size.height / 2);

        _graphOrigin = origin;
    }

return _graphOrigin;

}


A CGPoint is a struct, so you can't set it to nil or NULL (it's not a pointer). In a sense, there's really no "uninitialized" state. Perhaps you could use {0.0, 0.0} to designate an unset CGPoint, but that's also a valid coordinate. Or you could use negative x and y values to flag an "uninitialized" point, since negative values can't be valid drawing points, but that's a bit of a hack, too.

Probably your best bet is to do one of two things:

  1. Store the property as a pointer to a CGPoint. This value can be set to NULL when uninitialized. Of course, you have to worry about mallocing and freeing the value.
  2. Store the CGPoint alongside a BOOL called pointInitialized or somesuch, initially set to NO, but set to YES once the point has been initialized. You can even wrap that up in a struct:

    struct {
        CGPoint point;
        BOOL initialized;
    } pointData;
    

An easier way would be to initialize _graphOrigin to CGRectZero and change your if statement for this:

if (!CGPointEqualToPoint(_graphOrigin, CGPointZero)) {  

}

Create two CGPoint properties, that way they are both "uninitialized". Set one of them and use the second one to check whether or not they are equal.

@interface ClassName ()

@property (nonatomic) CGPoint point1;
@property (nonatomic) CGPoint point2;

@end

@implementation ClassName

self.point1 = CGPointMake(69.0f, 180.0f);  //arbitrary numbers

  //if not equal, then if statement proceeds
if (!CGPointEqualToPoint(self.point1, self.point2) {
    //your code here
}

@end

Idk if you'd consider this way hackish though. And I know your question was already answered, but I had kinda the same dilemma till I thought of this.


Since CGPointZero (0,0) and any other value you give a point may exist in your context you may want to initialize an NSValue with your point using:

NSValue *pointVal = [NSValue valueWithCGPoint:point];

You could do this based on some condition and then later test the NSValue for nil. NSValue can also be added to an array which would allow you to have an array of points should you need.

To get the point later simply use:

CGPoint point = [pointVal CGPointValue]; 






objective-c