0

在我的应用程序中,我正在向服务器发送请求。该请求位于其他一些名为 的类中requestClass,并且正在从主视图类中调用。(我正在使用 cocos2d)。

我的问题是,我将如何通知主班(来自requestClass)操作已完成?当它完成请求时,它的回调在它自己的 class( requestClass) 中,并且 NSLog 在requestClass.

我不认为NSNotification是正确的方法

requestClass 就像:

[NSURLConnection
     sendAsynchronousRequest:request
     queue:[[NSOperationQueue alloc] init]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {

         if ([data length] >0 && error == nil)
         {
             **// HOW SHOULD I INFORM THE CLASS THAT CALL ME NOW ???**

         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing ");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }

     }];
4

1 回答 1

1

好的,写一个委托协议......

假设您的连接文件名为 MyRequestClass。

在 MyRequestClass.h...

@protocol MyRequestClassDelegate <NSObject>

- (void)requestDidFinishWithDictionary:(NSDictionary*)dictionary;

//in reality you would pass the relevant data from the request back to the delegate.

@end

@interface MyRequestClass : NSObject // or whatever it is

@property (nonatomic, weak) id <MyRequestClassDelegate> delegate;

@end

然后在 MyRequestClass.h

[NSURLConnection
     sendAsynchronousRequest:request
     queue:[[NSOperationQueue alloc] init]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {

         if ([data length] >0 && error == nil)
         {
             [self.delegate requestDidFinishWithDictionary:someDictionary];

             //you don't know what the delegate is but you know it has this method
             //as it is defined in your protocol.
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing ");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }

     }];

然后在任何你想要的班级......

在 SomeOtherClass.h

#import "MyRequestClass.h"

@interface SomeOtherClass : UIViewController <MyRequestClassDelegate>

blah...

在 someOtherClass.m

MyRequestClass *requestClass = [[MyRequestClass alloc] init];

requestClass.delegate = self;

[requestClass startRequest];

...并确保也编写委托函数...

- (void)requestDidFinishWithDictionary:(NSDictionary*)dictionary
{
    //do something with the dictionary that was passed back from the URL request class
}
于 2013-02-05T10:16:07.347 回答