I want to store my CGPoint to the NSMutable Array, so , I have method like this:
[self.points addObject:CGPointMake(x, y)];
But I got the error
A simple way to handle CGPoint
(or any other non NSObject
inherited structure) is to create a new class inherited from NSObject
.
The code is longer, but clean. An example is below:
@interface MyPoint:NSObject
{
CGPoint myPoint;
}
- (id) init;
- (id) Init:(CGPoint) point;
- (BOOL)isEqual:(id)anObject;
@end
@implementation MyPoint
- (id) init
{
self = [super init];
myPoint = CGPointZero;
return self;
}
- (id) Init:(CGPoint) point{
myPoint.x = point.x;
myPoint.y = point.y;
return self;
}
- (BOOL)isEqual:(id)anObject
{
MyPoint * point = (MyPoint*) anObject;
return CGPointEqualToPoint(myPoint, point->myPoint);
}
@end
Here is some code sample showing the usage, do not forget to release!!!
//init the array
NSMutableArray *pPoints;
pPoints = [[NSMutableArray alloc] init];
// init a point
MyPoint *Point1 = [[MyPoint alloc]Init:CGPointMake(1, 1)];
// add the point to the array
[pPoints addObject:[[MyPoint alloc] Point1]];
//add another point
[Point1 Init:CGPointMake(10, 10)];
[pPoints addObject:[[MyPoint alloc] Point1]];
[Point1 Init:CGPointMake(3, 3)];
if ([pPoints Point1] == NO))
NSLog(@"Point (3,3) is not in the array");
[Point1 Init:CGPointMake(1, 1)];
if ([pPoints Point1] == YES))
NSLog(@"Point (1,1) is in the array");