NSMutableArray上的performSelector错误

时间:2012-09-11 22:22:07

标签: objective-c nsmutablearray performselector

你好我在NSMutableArray上使用performSelector有一个棘手的问题。我有可能误解了performSelector的作用。 基本上我有NSMutableArray与对象(所有这些都是基于我的类继承自UIButton的对象,但我认为这并不重要)我需要向数组中的所有对象发送消息。

在我的类的头文件中,我声明了函数,它由selector调用。它看起来像这样:

-(void)scaleChangedWithANumber:(NSNumber *)scale;

在此示例中,我的数组包含3个对象。如果我逐项称呼它们,那就完美了:

NSNumber *tmpNumber=[NSNumber numberWithFloat:scale];


ButtonOfElement *tmpButton1=[elementsButtonContainer objectAtIndex:0];
[tmpButton1 performSelector:@selector(scaleChangedWithANumber:) withObject:tmpNumber];

ButtonOfElement *tmpButton2=[elementsButtonContainer objectAtIndex:1];
[tmpButton2 performSelector:@selector(scaleChangedWithANumber:) withObject:tmpNumber];

ButtonOfElement *tmpButton3=[elementsButtonContainer objectAtIndex:2];
[tmpButton3 performSelector:@selector(scaleChangedWithANumber:) withObject:tmpNumber];

但是如果我尝试在数组上调用performSelector(我需要向数组中的所有对象发送消息):

NSNumber *tmpNumber=[NSNumber numberWithFloat:scale];
[elementsButtonContainer performSelector:@selector(scaleChangedWithANumber:) withObject:tmpNumber];
tmpNumber=nil;

我收到错误:

[__NSArrayM scaleChangedWithANumber:]: unrecognized selector sent to instance 0x1737f0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM scaleChangedWithANumber:]: unrecognized selector sent to instance 0x1737f0'
*** First throw call stack:
(0x34e456c3 0x370be97f 0x34e49227 0x34e47951 0x34d9f468 0x31d1 0x369a70eb 0x369a7447 0x369324d9 0x368f9c0d 0x36ae5649 0x3681df4f 0x3681c9b3 0x3682791f 0x368274eb 0x36814f29 0x36814843 0x337425d3 0x33742203 0x34e1a593 0x34e1a537 0x34e193b9 0x34d8c39d 0x34d8c229 0x3374131b 0x368688f9 0x2363 0x2308)
libc++abi.dylib: terminate called throwing an exception

我当然可以逐项使用循环和调用执行选择器,但我认为在数组上使用performSelector会更优雅,更清晰。

2 个答案:

答案 0 :(得分:11)

试试这个:

[elementsButtonContainer makeObjectsPerformSelector:@selector(scaleChangedWithANumber:) withObject:tmpNumber];

答案 1 :(得分:1)

elementsButtonContainer没有名为scaleChangedWithANumber的方法。您需要使用一些不同的逻辑声明它,或者在数组中的所有按钮子类上调用现有方法。