I am back again and this will be my second question of the day.
Anyways, I am using NSJSONSerialization to parse a data from my website. The data is in array format so I am using NSMutableArray. The problem is, I can’t access the data stored in NSMutableArray from different view controllers.
FirstView.h
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController
@property (nonatomic, strong) NSMutableArray *firstViewControllerArray;
@end
FirstView.m
- (void)ViewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://j4hm.t15.org/ios/jsonnews.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
self.firstViewControllerArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
}];
[self loadArray];
}
- (void)loadArray
{
NSMutableArray *array = [NSMutableArray arrayWithArray:[self firstViewControllerArray]];
//I also tried codes below, but it still won't work.
//[[NSMutableArray alloc] initWithArray:[self firstViewControllerArray]];
//[NSMutableArray arrayWithArray:[self.firstViewControllerArray mutableCopy]];
NSLog(@"First: %@",array);
SecondViewController *secondViewController = [[SecondViewController alloc] init];
[secondViewController setSecondViewControllerArray:array];
[[self navigationController] pushViewController:secondViewController animated:YES];
}
Second.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@property (nonatomic, strong) NSMutableArray *secondViewControllerArray;
@end
Second.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"Second: %@", [self secondViewControllerArray]);
}
Output
The NSLog(@"First: %@",array); will output the array hence it won’t be passing the SecondViewController a (null) value of the array.
However, NSLog(@"Second: %@", [self secondViewControllerArray]); will output (null). Am I missing something?
I don’t believe your download is completing before you push your new view controller onto the stack, and also set that view controller’s array property. Right now, you’re calling -loadArray right after you tell NSURLConnection to download data asynchronously. This download is going to finish long after you try to access the array property.
Try move the call to -loadArray within the asynchronous completion block (as seen below). Since this block is called when the download completes, you should have your data when you push the second view controller.