Objective-C Language CGPoint


One really good example of a struct is CGPoint; it's a simple value that represents a 2-dimensional point. It has 2 properties, x and y, and can be written as

typedef struct {
    CGFloat x;
    CGFloat y;
} CGPoint;

If you used Objective-C for Mac or iOS app development before, you've almost certainly come across CGPoint; CGPoints hold the position of pretty much everything on screen, from views and controls to objects in a game to changes in a gradient. This means that CGPoints are used a lot. This is even more true with really performance-heavy games; these games tend to have a lot of objects, and all of these objects need positions. These positions are often either CGPoints, or some other type of struct that conveys a point (such as a 3-dimensional point for 3d games).

Points like CGPoint could easily be represented as objects, like

@interface CGPoint {
    CGFloat x;
    CGFloat y;

... //Point-related methods (e.g. add, isEqualToPoint, etc.)

@property(nonatomic, assign)CGFloat x;
@property(nonatomic, assign)CGFloat y;


@implementation CGPoint

@synthesize x, y;



However, if CGPoint was used in this way it would take a lot longer to create and manipulate points. In smaller, faster programs this wouldn't really cause a difference, and in those cases it would be OK or maybe even better to use object points. But in large programs where points are be used a lot, using objects as points can really hurt performance, making the program slower, and also waste memory, which could force the program to crash.