fuzzygoat
fuzzygoat

Reputation: 26223

Creating Objects & Setting iVars in a Loop?

NSArray *planetArray = [NSArray arrayWithObjects:@"Earth", 
                                                 @"Jupiter", 
                                                 @"Saturn", 
                                                 @"Neptune", 
                                                 @"Pluto", nil];
NSMutableArray *objectArray = [[NSMutableArray alloc] init];

for(NSString *eachPlanet in planetArray) {
    Planet *newPlanet = [[Planet alloc] init];
    [newPlanet setValue:eachPlanet forKey:@"name"];
    [newPlanet setValue:@"TEST" forKey:@"type"];
    [newPlanet setValue:[NSNumber numberWithInt:1234] forKey:@"mass"];
    [objectArray addObject:newPlanet];
    [newPlanet release];
}

for(Planet *displayEachPlanet in objectArray) {
    NSLog(@"DATA: %@", displayEachPlanet);
}

[objectArray release];

I am curious if this is the best way to create an object and set an iVar for each item in an array. Basically I am:

  1. Creating a Planet object
  2. Setting the iVar (from the NSString array)
  3. Adding the Planet object to an array.
  4. Releasing the Planet object

  5. Printing my Planet objects

  6. Releasing the array

NB: I am just testing, this is not for anything, I was just curious ...

cheers Gary

Upvotes: 0

Views: 117

Answers (2)

davbryn
davbryn

Reputation: 7176

Can't see anything drastically wrong about doing it that way. One suggestion would be to have an extended initialiser for your planet class, along the lines of:

-(Planet*) initWithName:(NSString*)name andType:(NSString*)type withMass:(int)mass;

And then create the planet with:

Planet *newPlanet = [[Planet alloc] initWithName:eachPlanet andType:@"Test" withMass:42];

Upvotes: 3

Jesse Naugher
Jesse Naugher

Reputation: 9820

Looks good to me. If all you are doing with the objects is printing something from them, you could probably do it in one loop with less initializing and such, but if thats just a test..it looks fine.

Upvotes: 1

Related Questions