1

让我先说我是 Objective C 的新手。

我收到错误 atusMenuApp[24288:303] -[__NSCFConstantString createListItem]: unrecognized selector sent to instance 0x100002450

这是我的代码:

selector = [NSMutableArray arrayWithObjects: @"nvda", @"aapl", @"goog", nil];
[selector makeObjectsPerformSelector:@selector(createListItem:) withObject:self];

- (void)createListItem:(NSString *)title {
//do some stuff
}

现在我已经做了很多环顾四周,似乎这个问题的最大原因是增加或缺乏,:但我相信我正确地拥有它。也许我不太了解它的用法,makeObjectsPerformSelector因为在查阅了上面的文档后我发现:

Sends to each object in the array the message identified by a given selector, starting with the first object and continuing through the array to the last object.

任何帮助都会很棒,谢谢!

4

3 回答 3

4

[仅当您阅读文档(或思考一下为什么以这种方式而不是那种方式命名方法的原因),或者甚至努力尝试理解错误消息时...]

makeObjectsPerformSelector:withObject:方法按照NSArray它的建议做:它使数组的对象执行选择器,它可以有一个可选的参数。所以

[selector makeObjectsPerformSelector:@selector(createListItem:) withObject:self];

createListItem:消息发送到数组中的每个NSString对象并作为其参数selector传入。它不会在传递对象时执行选择器。即,你所拥有的相当于selfself

for (NSString *obj in selector) {
    [obj createListItem:self];
}

显然,您需要以下内容,而不是这个:

for (NSString *obj in selector) {
    [self createListItem:obj];
}

你甚至不需要那种讨厌的方法。一个不错的快速枚举for循环会做到这一点。

于 2012-12-31T00:05:34.353 回答
1

首先,您制作一个 s 数组NSString。然后,您向他们发送所有消息createListItem。这一切都很好,花花公子,但NSString没有任何方法被调用createListItem;仅仅因为您定义了一个名为的实例方法createListItem并不意味着每个类的每个实例都可以使用它。只有实现文件中有定义的类才能处理消息。例如,我不能列出Car实例,然后fly在另一个名为Helicopter' 实现的类中定义方法,并期望能够调用fly; 的实例Car。只能Helicopter使用它。我建议你阅读一本关于 Objective-C 的好书,并进一步熟悉类、实例和实例方法。

于 2012-12-31T00:05:25.950 回答
1

你误解了方法。

它将在每个对象上调用createListItem:带有参数的方法。selfNSArray

因此,结果调用将类似于:

[@"nvda" createListItem:self];
...

显然,a 不存在该方法,NSString并且您的异常出现了。

如果您需要对self数组中的每个对象应用一个方法,只需循环遍历它。

于 2012-12-31T00:05:52.873 回答