views:

79

answers:

1

I'd like to change the value of a parameter at runtime and curious how this works in Obj-C.

I have a loop where value of 'n' is 0 increasing by 1 with each loop. How does one increment the passed parameter by 1 as n moves.

UIViewSubclass *uiViewSubclass = [[UIViewSubclass alloc] initWithValue:([value integerValue]) 
                  andPlacement:kPlacement0;

next time through loop I'd like 2nd argument to read as: andPlacement:kPlacement1; and then: andPlacement:kPlacement2; and on...

do I make kPlacement a string and stringByAppendingString:[[NSNumber numberWithInt:n] stringValue]; ?

What's the Obj-C/Cocoa approach?

+3  A: 

You can't modify your source code or make up variable references at runtime. Objective-C isn't that dynamic.

If the values of kPlacement0 through kPlacementMax are sequential, you may be able to use a for loop to step through them directly:

for (MyPlacement placement = kPlacement0; placement += kPlacementIncrement; placement <= kPlacementMax) {
 UIViewSubclass *instanceOfUIViewSubclass = [[UIViewSubclass alloc] initWithValue:([value integerValue])
                                                                     andPlacement:placement];
 //Do something with instanceOfUIViewSubclass.
 [instanceOfUIViewSubclass release];
}

(You will need to define kPlacementIncrement and kPlacementMax in addition to the kPlacement0, etc. constants. I'm using MyPlacement as the name of your enumeration type that the kPlacement0 etc. constants correspond to.)

If they are not sequential, put them in a C array and iterate on that array:

enum { numPlacements = <#Insert the number of placement constants here#> };
MyPlacement placements[numPlacements] = {
 kPlacement0,
 kPlacement1,
 kPlacement2,
 ⋮
}

for (unsigned i = 0U; i < numPlacements; ++i) {
 UIViewSubclass *instanceOfUIViewSubclass = [[UIViewSubclass alloc] initWithValue:([value integerValue])
                                                                     andPlacement:placements[i]];
 //Do something with instanceOfUIViewSubclass.
 [instanceOfUIViewSubclass release];
}

You probably can come up with more-descriptive names than kPlacement0 etc. When you want to refer to them by number, do that; when you want to refer to them by name, give them good names.

Peter Hosey
To be more explicit: Anytime you find yourself tempted to have a bunch of variables named `suchandsuch1`, `suchandsuch2`, etc., you probably meant to use an array.
Chuck