从NSObject类返回并在viewcontroller类中使用的nsdata

时间:2014-03-03 12:28:17

标签: ios objective-c

我有一个包含3种方法的NSObject类:

-(void)RequestForData
{
    #pragma Mark - ASIHTTPRequest

     NSURL *url=[NSURL URLWithString:@"http://srv2.vitaminas.it/pdv"];
     ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:url];
     [request setDelegate:self];
     [request startSynchronous];

}

pragma Mark - HTTP Delegate

- (NSData*)requestFinished:(ASIHTTPRequest *)request
{

    NSData *responseData = [request responseData];

   return responseData;

}


- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);

} 

我有一个视图控制器类,来自viewDidLoad viewcontroller类调用方法 - RequestForDataNSObject方法,

WebServiceMethods *web=[[WebServiceMethods alloc]init];

[web RequestForData];

arr_JsonData=[NSJSONSerialization JSONObjectWithData:web  options:NSUTF8StringEncoding error:Nil];

NSLog(@"%@",arr_JsonData);

[self.tableView reloadData];

但我想使用从NSData类(即NSObject)返回的return responsedata;到视图控制器类中。

我想将NSData放入arr_JsonData(NSMutuableArray

我该怎么办?

2 个答案:

答案 0 :(得分:0)

responseData作为类级别变量。不要在requestFinished方法中创建它的本地实例。

答案 1 :(得分:0)

你的问题是回调。您应该将viewController作为WebServiceMethods的代表(或使用阻止更好),以便在请求完成后填充并填充您的arr_JsonData

@protocol WebServiceMethodsDelegate

- (void)webServiceMethodsDidFinishWithSucess:(NSString *)response; // give this méthode an appropriate name.
- (void)webServiceMethodsDidFailWithError:(NSError *)error;
@end


@interface WebServiceMethods : NSObject

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

@end

@implemntation WebServiceMethods : NSObject


- (void)requestFinished:(ASIHTTPRequest *)request
{
   NSString *responseString = [request responseString];
  [self.delegate webServiceMethodsDidFinishWithSucess:responseString];

}

- (void)requestFailed:(ASIHTTPRequest *)request
{
   NSError *error = [request error];
[self.delegate webServiceMethodsDidFailWithError:error];
}

@end

使您的viewController符合WebServiceMethodsDelegate协议。

@interface yourViewController : UIViewController <WebServiceMethodsDelegate>
...
@end

并在viewController的viewDidLoad中知道:

WebServiceMethods *web=[[WebServiceMethods alloc]init];
web.delegate = self;

[web RequestForData];

将委托方法放在viewController.m

- (void)webServiceMethodsDidFinishWithSucess:(NSString *)response {
// here you can parse the response and reload your tableView
.....
[self.tableView reloadData];
}

- (void)webServiceMethodsDidFailWithError:(NSError *)error {
// handle the errors
}

PS:您的代码存在许多问题:

  1. 请勿使用ASHTTPRequest,不予维护。您可以使用AFNetworkingAFNetworking

  2. 将您的WebServiceMethods作为共享实例。

  3. ...