我想在NSObject类中添加MBProgressHUD

时间:2012-11-02 14:46:26

标签: iphone ios mbprogresshud

我从我的NSObject类上传服务器上的数据,现在我想在上传数据时显示MBProgressHUD,我知道如何用ViewController显示MBProgressHUD但不知道如何用NSObject类显示它。

6 个答案:

答案 0 :(得分:2)

AppDelegate* delegate = [[UIApplication sharedApplication] delegate];
[delegate.window addSubview:HUD];
...
[HUD removeFromSuperview];

答案 1 :(得分:2)

有几种方法可以解决这类问题。最常见的是使用委托模式,但您可以使用块,KVO或通知。

您应该从创建协议开始,这样您就可以在UIViewController和拨打电话的NSObject之间进行通信。虽然您不需要创建此通信,但您应该使用它来获得更灵活的代码。

通常情况下,我会这样做:

@protocol CommunicationDelegate <NSObject>

@required

-(void)communicationSucceed;

-(void)communicationFailedWithError:(NSError*)anError;

NSObject内,您将获得符合协议weak的对象的CommunicationDelegate引用。在你的.h你应该有这样的东西:

@property(nonatomic, weak) id <CommunicationDelegate> communicationDelegate;

在您真正开始使用NSObject之前,您应该这样做:

myObjectThatWillDoSomething.communicationDelegate = self;

目前,您在UIViewControllerNSObject之间拥有有效的引用。在你的UIViewController的.h文件中,添加:

@interface myViewController : UIViewController <CommunicationDelegate>

因此,您的UIViewController符合CommunicationDelegate协议。

您现在可以从MBProgressHUD开始UIViewController了。在NSObject完成工作后,您可以致电:

[communicationDelegate communicationSucceed];

[communicationDelegate communicationFailedWithError:anError]; //anError is used to describe what went wrong

一旦(其中一个)方法被调用,您就可以删除MBProgressHUD。了解在UIViewController内调用此方法。

答案 2 :(得分:0)

当您上传NSObject时,会显示一个视图,对吧?因此,在该视图中显示您的HUD。您可能需要创建一个委托,以便在下载开始时,结束时以及出现错误时通知视图。

答案 3 :(得分:0)

使用NSNotification Center停止指示符,在视图控制器中使用侦听方法声明NSNotification。并从Webservice文件发布通知。在通知中心的收听方法中停止指示。

此链接可以帮助您

答案 4 :(得分:0)

在您的上传器对象上创建委托协议

@protocol UploaderThingyDelegate <NSObject>

-(void)stuffStarted;

-(void)stuffEnded;

@end

@interface UploaderThingy : NSObject

@property (weak) id<UploaderThingyDelegate> delegate;

将相关的View或ViewController设置为上传者委托并触发MBProgressHUD添加/删除。

答案 5 :(得分:-1)

以下代码在NSObject文件中正常工作

第1步:下载 https://github.com/jdg/MBProgressHUD

步骤2:添加Delegate MBProgressHUDDelegate

步骤3:声明实例MBProgressHUD * HUD;

步骤4:编写您想要的代码:

HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
[[UIApplication sharedApplication].keyWindow addSubview:HUD];

HUD.delegate = self;
HUD.labelText = @"Processing";
[HUD show:YES];