0

我正在尝试解决以下问题。我的头文件中有以下常量:

#define PREFS_MY_CONSTANT_1 @"bla1"
#define PREFS_MY_CONSTANT_2 @"bla2"
#define PREFS_MY_CONSTANT_3 @"bla3"
...

在我的一个函数中,我想根据用户输入将这些字符串之一打印到 UIbutton,所以说用户输入“1”,我会显示 bla1。我没有创建一个巨大的开关(我有 100 个),而是寻找一种将常量与保存用户输入的变量结合起来的方法,所以理想情况下是这样的:

NSInteger input;
[button setTitle:PREFS_MY_CONSTANT_{$input} forState: UIControlStateNormal];

这样的事情可能吗?解决这个问题的最佳方法是什么?

4

3 回答 3

4

I'd define a plain C array of NSString literals:

static NSString *prefs[] = {
    @"foo",
    @"bar",
    @"baz",
};

Either use a 0-based index, or put something in the first entry you won't use, like nil. Then prefs[input] will give you the string you want.

(The comma after the last entry isn't a mistake. It allows you to add more entries without first having to add a comma. It makes it easier to edit, and makes revision history easier to read.)

The number of elements in a static array can be determined at compile time. I usually use a macro for this:

#define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))

Then you can compare the user input against ARRAYSIZE(prefs) to make sure it stays within the range.

于 2012-10-25T05:08:04.730 回答
2

another way is to use NSArray for this.

create an array like this:

NSArray *titleArray = [[NSArray alloc] initWithObjects:@"bla1",@"bla2",@"bla3", nil];

and you can set the title of button following way:

[button setTitle:[titleArray objectAtIndex:input] forState: UIControlStateNormal];
于 2012-10-25T05:08:25.653 回答
0

为此NSString,作为

NSString *input = [NSString stringWithFormat:@"PREFS_MY_CONSTANT_%@",input];
[button setTitle:input forState: UIControlStateNormal];

          or
 [button setTitle:[NSString stringWithFormat:@"PREFS_MY_CONSTANT_%@",input] forState:     UIControlStateNormal];

让我知道它是否有用。

谢谢和问候, 阿尼尔

于 2012-10-25T05:00:43.710 回答