views:

105

answers:

5

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

How can this be done? I suspect using an NSMutableArray?

A: 

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

It's not terribly difficult to use one either:

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

As Brad Larson pointed out, this is for Mac, not for iPhone.

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

One solution is to wrap the center struct with 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 to, for example, wrapping an int with NSNumber for storage in an array.)

andyvn22
Note that `+valueWithPoint:` and `-pointValue` do not exist on the iPhone, only on the Mac. You can use `+valueWithCGPoint:` and `-CGPointValue` on the iPhone (what he's interested in, judging from the tags), as I describe in my answer.
Brad Larson
Thanks for that; I'm not an iPhone-er.
andyvn22
A: 

You have a slew of options for doing this.

The thing to remember is that the x and y values are going to be CGFloats (and image.center a CGPoint). These are not objects, and can not be added directly to an NSArray.

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

Jerry Jones
Thanks guys. There were certainly plenty of options available. Thank you for being so helpful and explaining with code!
mac_newbie
+3  A: 

I would recommend storing the points in an NSArray, wrapped using NSValue:

NSMutableArray *arrayOfPoints = [[NSMutableArray alloc] init];

[arrayOfPoints addObject:[NSValue valueWithCGPoint:image.center];

// Do something with the array
[arrayOfPoints release];

This assumes that image.center is a CGPoint struct (if not, you can make one using CGPointMake()).

To extract the CGPoint, simply use

[[arrayOfPoints objectAtIndex:0] CGPointValue];
Brad Larson
+2  A: 

C arrays are a proper subset of Objective C, as well as producing faster code and often using less memory than using Cocoa Foundation classes. You could add:

CGPoint myPoints[MAX_NUMBER_OF_POINTS];

to your instance variables; and save coordinates with:

myPoints[i] = image.center;
hotpaw2
+1 if you're using *lots* of points, this might be the best way, since you don't have the overheard of creating tons and tons of `NSValue` objects.
Dave DeLong