0

Basically I have an NSMutableArray set up like so, with instances of another class as the array elements.

[[NSMutableArray alloc] initWithObjects: [[Shape alloc] init], [[Shape alloc] init], nil];

Each of the shape classes has an instance variable that holds what kind of shape it is. I want to be able to make this array so that it assigns a value to the instance variable, something like this, where ShapeVariable is the instance variable in the Shape class, and Square/Circle is the value I want it to have.

[[NSMutableArray alloc] initWithObjects: [[Shape alloc] initwith ShapeVariable Square], [[Shape alloc] initwith ShapeVariable Circle], nil];

Also, I would like to know how to assign two instance variables at the same time to the same element.

5
  • 2
    This smells soooo bad.... Also, you're leaking every single Shape object. Commented Sep 11, 2010 at 4:45
  • Well, then I would like to know how to do it an alternative way so it doesn't "smell soooo bad" Commented Sep 11, 2010 at 14:26
  • the proper way to do it is to make sure each Shape object is fully initialized before it ever goes in to the array. Or if you need to alter the state of a Shape object, retrieve a pointer to the object ([array objectAtIndex:42]) and then manipulate the Shape directly. Absolutely don't use the array to directly manipulate the objects for you. An array is just a container, nothing more. Commented Sep 11, 2010 at 17:05
  • @Dave Delong Alright, so how about something like this: Commented Sep 11, 2010 at 20:44
  • shape1 = [[Shape alloc] init] Then the same thing for shape two and then I could have a method in the shape class that changes ShapeVariable, call that, and then put them into the array. However, this seems to be sort of inefficient, is there a different way of doing this? Commented Sep 11, 2010 at 20:51

1 Answer 1

1

The developer tools installation includes an example called Sketch. It basically does exactly what you want and is very carefully reviewed by the team that develops the Cocoa framework with every release of the OS to make sure that it follows the "most modern" rules and APIs.

Regardless of whether or not your final goal is to target the iPhone, starting with that example will likely prove to be extremely useful.

You'll find it in /Developer/Examples/Sketch/.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.