views:

56

answers:

1

I've got a int, that is changed in a previous method, that now has to be part of the name of a button variable. For example:

int numberFromLastOne;
numberFromLastOne = 4;

I then want to get 'button4' to do something. Could I use something like this?

[[button@"%d", numberFromLastOne] doSomething:withSomethingElse];

I've never had to do something this before. Any ideas would be appreciated :)

+3  A: 

I'm not exactly sure what you're trying to do, but if you have a series of buttons, and you're trying to retrieve one of them based on some integer value, you could use the tag property to do this.

Give the buttons numeric tags (in IB, or programmatically, however you're creating your UI). Then at runtime do something like:

int numberFromLastOne;
numberFromLastOne = 4;
UIButton* aButton = (UIButton*) [self.view viewWithTag:numberFromLastOne];

That assumes you're doing this from a view controller; you didn't say. You get the idea, look up the viewWithTag member.

zpasternack
would this throw and exception if the int is 0?because isnt the defaul tag for everything 0?
Sam Jarman
your method is working btw
Sam Jarman
Ok... it seems it does. I just pushed the values of all the tags up 1 - hence removing tag 0. Thanks though!
Sam Jarman
The Cocoa equivalent would be NSMatrix's `cellWithTag:` method: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSMatrix_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMatrix/cellWithTag: Note that most views in AppKit do not have tags; only controls and cells do, along with menu and toolbar items. An NSMatrix is a view that hosts a two-dimensional array of cells.
Peter Hosey