iOS:如何定义公共方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10853285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS: How to define public methods?
提问by 88fsantos
How can I define a method that can be called from anywhere, in every viewcontroller class?
如何在每个视图控制器类中定义一个可以从任何地方调用的方法?
I have a method that brings me a json file, and i want it to be reusable, since i have several json calls on my app.
我有一个方法可以给我一个 json 文件,我希望它可以重用,因为我的应用程序上有几个 json 调用。
Can you help me?
你能帮助我吗?
采纳答案by Kaan Dedeoglu
You can add it through a category:
您可以通过类别添加它:
EDIT
编辑
Create a new .h .m file pair and in the .h file:
创建一个新的 .h .m 文件对并在 .h 文件中:
@interface UIViewController(JSON)
-(void) bringJSON;
-(void) fetchData:(NSData*) data;
@ end
Then in the .m file:
然后在 .m 文件中:
@implementation UIViewController(JSON)
-(void) bringJSON {
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[NSData dataWithContentsOfURL:yourURL];
[self performSelectorOnMainThread:@selector(fetchData:)
withObject:data waitUntilDone:YES];
});
}
-(void) fetchData:(NSData*) data {
//parse - update etc.
}
@end
Where I'm just assuming that you'll be returning an NSArray, you can put any method there and extend all UIViewControllers. The method bringJSON will be available to all UIViewControllers and its subclasses.
我只是假设您将返回一个 NSArray,您可以在那里放置任何方法并扩展所有 UIViewController。所有 UIViewControllers 及其子类都可以使用该方法 becomeJSON。
回答by rooster117
I believe you are thinking about a static method which would be defined with the "+" symbol.
我相信您正在考虑使用“+”符号定义的静态方法。
+ (String) yourFunctionName:(NSInteger)someValue .....
Then you could call it anywhere with the class name first:
然后你可以先用类名在任何地方调用它:
[YourClassName yourFunctionName:5];
If you need to have a function that access an object that needs to be instantiated then you will want to do a singleton pattern.
如果您需要一个函数来访问需要实例化的对象,那么您将需要执行单例模式。
回答by Jignesh B
Use a + sign before the return type of the method.
在方法的返回类型前使用 + 号。
For example:
例如:
+ (void) Name: (NSString *) str{
}
回答by trumpetlicks
I plused the first answer as it is a way of creating (essentially) another object with methods that can be called from any file that includes that object.
我加上第一个答案,因为它是一种创建(本质上)另一个对象的方法,该对象的方法可以从包含该对象的任何文件中调用。
Remember also that objective-c also is simply just C. You can have .c files included that are simply contain ANSI-C routines that can be called also.
还请记住,objective-c 也只是 C。您可以包含 .c 文件,这些文件仅包含也可以调用的 ANSI-C 例程。