I'm trying to develop an app to receive data from a web service to be displayed in some views. In the first version of the app I've only one view controller and one GET request to the web service (by means of NSURLconnection): all the methods for the NSURLconnection are in the Viewcontroller and everything is working well.
Now I would need to add other views and make some other GET requests so I was thinking that the best thing is to apply the MVC pattern: in particular I have created a class (FV_Data) where I put all the GET requests and manage the NSURLconnections, while in each ViewController I call the method (in the FV_Data class) for the needed GET request.
My problem is how to return the array with the data from the web service to the ViewController that asked for the data: in my first tests, the NSURLconnection is correctly started and the array (in the connectionDidFinishLoading method) is filled with the data from the web service but in the View Controller the array is empty.
I've read different posts but I can't understand what I'm doing wrong.
This is the code that I've written (I omit the code in methods that work).
Thanks, Corrado
FV_Data.h
#import <Foundation/Foundation.h>
@interface FV_Data: NSObject {
NSMutableData *responseStatistic;
NSMutableData *responseGetStatus;
NSURLConnection *connectionStatistic;
NSURLConnection *connectionGetStatus;
}
-(NSArray *)richiediGetStatistic;
-(NSArray *)richiediGetStatus;
@property (nonatomic, retain) NSArray *ArrayStatistic;
@property (nonatomic, retain) NSArray *ArrayGetStatus;
@end
FV_Data.m
#import "FV_Data.h"
@implementation FV_Data
-(id)init {
self = [super init];
return self;
}
-(void)richiediGetStatistic{
...
}
-(void)richiediGetStatus{
...
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
...
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
...
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if(connection == connectionStatistic){
NSString *responseStatisticString = [[NSString alloc] initWithData:responseStatistic encoding:NSUTF8StringEncoding];
self.ArrayStatistic = [responseStatisticString componentsSeparatedByString:@","];
}
else if(connection == connectionGetStatus){
NSString *responseGetStatusString = [[NSString alloc] initWithData:responseGetStatus encoding:NSUTF8StringEncoding];
self.ArrayGetStatus = [responseGetStatusString componentsSeparatedByString:@","];
}
}
@end
FV_Live_ViewController.h
#import <UIKit/UIKit.h>
#import "FV_Data.h"
@interface FV_Live_ViewController : UIViewController {
IBOutlet UILabel *energia;
}
@property (nonatomic, retain) FV_Data *PVOutputData;
@end
FV_Live_ViewController.m
#import "FV_Live_ViewController.h"
@implementation FV_Live_ViewController
-(void)viewWillAppear:(BOOL)animated{
self.PVOutputData = [[FV_Data alloc] init];
[self.PVOutputData richiediGetStatistic];
energia.text = [self.PVOutputData.ArrayStatistic objectAtIndex:0];
}
@end