iOS: How to define public methods?

三世轮回 提交于 2019-12-04 19:54:14

问题


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.

Can you help me?


回答1:


You can add it through a category:

EDIT

Create a new .h .m file pair and in the .h file:

@interface UIViewController(JSON)
-(void) bringJSON;
-(void) fetchData:(NSData*) data;


@ end

Then in the .m file:

@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.




回答2:


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.




回答3:


Use a + sign before the return type of the method.

For example:

 + (void) Name: (NSString  *) str{

 }



回答4:


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.



来源:https://stackoverflow.com/questions/10853285/ios-how-to-define-public-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!