How to save (x, y) coordinates in an array using Objective-C?

I have an Objective-C method that uses some x and y values ​​from an image: image.center.x and image.center.y . I want to store them every time this method is called, so I was hoping to use an array.

How can I do that? I suspect the use of NSMutableArray?

+4
source share
5 answers

I would recommend storing dots in NSArray wrapped using NSValue:

 NSMutableArray *arrayOfPoints = [[NSMutableArray alloc] init]; [arrayOfPoints addObject:[NSValue valueWithCGPoint:image.center]]; // Do something with the array [arrayOfPoints release]; 

image.center is supposed to be a image.center framework (if not, you can do it with CGPointMake() ).

To extract CGPoint just use

 [[arrayOfPoints objectAtIndex:0] CGPointValue]; 
+12
source

C arrays are a proper subset of Objective-C, and they also create faster code and often use less memory than using Cocoa Foundation classes. You can add:

 CGPoint myPoints[MAX_NUMBER_OF_POINTS]; 

to your instance variables; and save the coordinates with:

 myPoints[i] = image.center; 
+6
source

As Brad Larson noted, this is for the Mac, not for the iPhone.

Yes, NSMutableArray is the best option. However, arrays store objects, and the center is a structure!

One solution is to wrap around the center structure using NSValue :

 yourArray = [NSMutableArray arrayWithCapacity:2]; //Don't worry, capacity expands automatically [yourArray addObject:[NSValue valueWithPoint:image.center]]; //later [[yourArray objectAtIndex:whatevs] pointValue]; 

(This is very similar, for example, to int packaging with NSNumber for storage in an array.)

+2
source

You have many options for this.

Keep in mind that the x and y values ​​will be CGFloats (and image.center CGPoint). These are not objects and cannot be added directly to NSArray.

You can use the NSValue valueWithPoint: and pointValue methods. If you want to save them yourself, you can use NSNumber by executing [NSNumber numberWithFloat: x] ;. Or, if you want, you can use C arrays.

+2
source

You are correct that you must have the type NSMutableArray to modify the array.

It is not very difficult to use one of them:

 NSMutableArray* array = [NSMutableArray arrayWithCapacity:3]; [array addObject:firstObject]; [array addObject:secondObject]; [array addObject:thirdObject]; 
+1
source

All Articles