1

我有很多按钮,我想在加载视图时给它们一个标题。按钮的标题根据月份中的哪一天而有所不同。因此,我创建了一个包含所有按钮名称的数组。我的代码如下:

我的界面:

@property (strong, nonatomic) IBOutlet UIButton *button1;
@property (strong, nonatomic) IBOutlet UIButton *button2;
@property (strong, nonatomic) IBOutlet UIButton *button3;
@property (strong, nonatomic) IBOutlet UIButton *button4;
@property (strong, nonatomic) IBOutlet UIButton *button5;
@property (strong, nonatomic) IBOutlet UIButton *button6;
@property (strong, nonatomic) IBOutlet UIButton *button7;
@property (strong, nonatomic) IBOutlet UIButton *button8;
@property (strong, nonatomic) IBOutlet UIButton *button9;
@property (strong, nonatomic) IBOutlet UIButton *button10;

我的实现:

@synthesize button1 = _button1;
@synthesize button2 = _button2;
@synthesize button3 = _button3;
@synthesize button4 = _button4;
@synthesize button5 = _button5;
@synthesize button6 = _button6;
@synthesize button7 = _button7;
@synthesize button8 = _button8;
@synthesize button9 = _button9;
@synthesize button10 = _button10;

NSArray *myArray = [NSArray arrayWithObjects: @"dummyButton", @"_button1", @"_button2", @"_button3", @"_button4", @"_button5", @"_button6", @"_button7", @"_button8", @"_button9", @"_button10", nil];

for (int i = varDefinedEarlier; i<=totalAmountOfNeededTitles; i++) {
     NSString *theTitleSting = [NSString stringWithFormat:@"%i",i];
     NSLog(@"arrayValue:%@", [myArray objectAtIndex:i]); //Works prints the button name (for example _button7)


    [[myArray objectAtIndex:i] setTitle:theTitleSting forState:UIControlStateNormal];
//The line above is where the app crashes. Everything else works just fine.
}

提供给我的错误是“线程 1:信号 SIGABRT

除此之外,这就是日志所说的:

-[__NSCFConstantString setTitle:forState:]:无法识别的选择器发送到实例 0x14a48 2012-07-10 22:57:49.649 不要破坏链 [10302:707] * * * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因: ' - [__ NSCFConstantString的setTitle:forState:]:发送到实例0x14a48无法识别选择' * * *第一掷调用堆栈:(0x3774788f 0x3544c259 0x3774aa9b 0x37749915 0x376a4650 0xdc2f 0x31454c8b 0x314611e9 0x31461059 0x31460f3f 0x3146070b 0x31460503 0x31454aff 0x314547d5 0x314cd903 0x31547627 0x37fb8933 0x3771ba33 0x3771b699 0x3771a26f 0x3769d4a5 0x3769d36d 0x33e5c439 0x31449cd5 0xb7cf 0xb774)终止调用抛出异常(lldb)

我认为错误是我试图告诉应用程序女巫按钮它需要设置标题的方式,但我无法真正弄清楚如何让它接受我的数组的值并将其用作按钮名称。

我是 iPhone iOS 开发的新手,如果答案很简单,请耐心等待;)

4

2 回答 2

2

您没有引用按钮实例,而是引用该数组中的一些字符串。现在在您的循环中,您尝试在那些不存在 NSString 实例的字符串上调用 setTitle:forState: 方法。

尝试以下操作:

NSArray *myArray = [NSArray arrayWithObjects:_button1, _button2, _button3, _button4, _button5, _button6, _button7, _button8, _button9, _button10, nil];

这将按预期将实际按钮实例放入您的数组中,并且您的代码应该可以正常工作。

于 2012-07-10T21:14:59.657 回答
1

你应该做类似的事情[myButton setTitle:[myArray objectAtIndex:i] forState: UIControlStateNormal]

目前,您正在将 setTitle 消息传递给字符串类型,这当然会导致崩溃……希望对您有所帮助

于 2012-07-10T21:15:26.733 回答