简体   繁体   English

为什么我不能调用此方法?

[英]Why I can't call this method?

I have a method signature here: 我在这里有一个方法签名:

.h

-(void)addToArray

And I want to use it here: 我想在这里使用它:

.m 

-(void)viewDidLoad{
NSMutableArray *array = [[NSMutableArray alloc]init];
[array addToArray];
}

-(void)addToArray{
//some code here…
}

The problem is that when I do [array addToArray]; 问题是当我这样做时[array addToArray]; it returns to me a message that says "Instance method '-addToArray' not found (return type defaults to 'id')" How can I solve it? 它向我返回一条消息,提示“找不到实例方法'-addToArray'(返回类型默认为'id')”我该如何解决?

when you do [array somemethod] ..it will look for the method in that array data type class( that is in NSMutableArray class. 当您执行[array somemethod] ..时,它将在该数组数据类型class(即NSMutableArray类中)中查找该方法。

when you have a method in your own class.and it is not a category...then you must call 当您在自己的类中有一个方法而不是类别时,则必须调用

[self somemethod]

this way it will look in the class that is in which you are calling the method. 这样,它将在您正在调用方法的类中查找。

Change to: 改成:

.h 。H

-(void)addObjectsToArray:(NSMutableArray*)a;

.m .m

- (void)viewDidLoad {
     NSMutableArray * array = [[NSMutableArray alloc]init];
     [self addObjectsToArray:array];
}
- (void)addObjectsToArray:(NSMutableArray*)a {
     //some code here…
     [a addObject:[NSString stringWithFormat:@"Example String Object"]]; // example way to add objects to the array
}

Shubhank's answer is indeed correct, however if you want to accomplish what you'd initially described, that is have the have the NSMutableArray instance respond to your method, you can achieve that through the use of categories. Shubhank的回答确实是正确的,但是,如果您想完成您最初描述的内容,即让NSMutableArray实例响应您的方法,则可以通过使用类别来实现。 https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html

This blog details adding a category to NSArray and/or NSMutableArray. 该博客详细介绍了如何向NSArray和/或NSMutableArray添加类别。 http://it.toolbox.com/blogs/macsploitation/extending-classes-in-objectivec-with-categories-27447 http://it.toolbox.com/blogs/macsploitation/extending-classes-in-objectivec-with-categories-27447

In your m file, try doing this: #import "whatever its called.h" if you haven't yet. 在您的m文件中,尝试执行以下操作:#import如果尚未调用,无论其为“ .h”。 If you provide more code I can give more help, but I hope this helps. 如果您提供更多代码,我可以提供更多帮助,但是希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM