iOS:如何定义公共方法? [英] iOS: How to define public methods?

查看:82
本文介绍了iOS:如何定义公共方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在每个viewcontroller类中定义一个可以从任何地方调用的方法?

How can I define a method that can be called from anywhere, in every viewcontroller class?

我有一个方法可以为我带来一个json文件,我想要它可以重复使用,因为我的应用程序上有几个json调用。

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.

你能帮助我吗?

推荐答案

您可以通过以下类别添加:

You can add it through a category:

编辑

在.h文件中创建一个新的.h .m文件对:

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

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


@ end

然后在.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

我假设您将返回NSArray,您可以在其中放置任何方法并扩展所有UIViewControllers。方法bringJSON将可用于所有UIViewControllers及其子类。

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.

这篇关于iOS:如何定义公共方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆