How do I add a CGPoint to NSMutableArray?

前端 未结 6 1904
小蘑菇
小蘑菇 2021-02-01 13:58

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

6条回答
  •  忘了有多久
    2021-02-01 14:32

    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:

    In .h file:

    @interface MyPoint:NSObject
    {
         CGPoint myPoint;   
    }
    
    - (id) init;
    - (id) Init:(CGPoint) point;
    - (BOOL)isEqual:(id)anObject;
    
    @end
    

    In .m file:

    @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");
    

提交回复
热议问题