Daniel
Daniel

Reputation: 31559

Nullable in objective c

Is there a way to make nullable struct in objective C like in C# you can use Nullable<T>?
I need a CGPoint to be null when there is no applicable value. I cannot allocate a random invalid value for this like (-5000, -5000) because all values are valid for this.

Upvotes: 3

Views: 3250

Answers (4)

madmik3
madmik3

Reputation: 6973

CGPoint is a struct and that has some different rules in objective-c than you might think. You should consider reading about structs in objective-c.

The way this is done most of the time is to wrap the struct in an object because that object can be set to null. NSValue will wrap a CGPoint.

NSValue * v = [NSValue valueWithPoint:CGPointMake(1,9)];
NSVAlue * vNull = [NSValue valueWithPointer:nil];
if([v objCType] == @encode(CGPoint)) printf("v is an CGPoint");

Upvotes: 3

Magic Bullet Dave
Magic Bullet Dave

Reputation: 9076

There is also nothing stopping you creating your own struct based on CGPoint, similar to how C# 2 works.

struct NilableCGPoint { bool isNil; CGPoint point; }

Examples of use:

// No value (nil)
NilableCGPoint myNilablePoint.point = CGPointZero;
myPoint.isNil = YES;

// Value of (0,0)
NilableCGPoint myNilablePoint.point = CGPointZero;
myPoint.isNil = NO;

// Value of (100, 50)
NilableCGPoint myNilablePoint.point = CGPointMake(100, 50);
myPoint.isNil = NO;

Upvotes: 0

highlycaffeinated
highlycaffeinated

Reputation: 19867

What if you define a CGPoint using CGPointMake(NAN, NAN) similar to CGRectNull? Surely with NAN's for coordinates, it's not still a valid point.

Upvotes: 8

David Beck
David Beck

Reputation: 10159

CGPoint is a enum, not an object. You can use CGPointZero, or you can wrap all of your points inside of NSValue, which are objects and can be nil.

Upvotes: 1

Related Questions