我有一个包含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];
}
- (NSData*)requestFinished:(ASIHTTPRequest *)request
{
NSData *responseData = [request responseData];
return responseData;
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(@"%@",error);
}
我有一个视图控制器类,来自viewDidLoad
viewcontroller类调用方法 - RequestForData
类NSObject
方法,
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
)
我该怎么办?
答案 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:您的代码存在许多问题:
请勿使用ASHTTPRequest
,不予维护。您可以使用AFNetworking
。AFNetworking
将您的WebServiceMethods作为共享实例。
...