我又回来了,这将是我当天的第二个问题。
无论如何,我正在使用NSJSONSerialization
来解析我网站上的数据。数据采用数组格式,因此我使用NSMutableArray
。问题是,我无法从不同的视图控制器访问NSMutableArray
中存储的数据。
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]);
}
输出
NSLog(@"First: %@",array);
将输出数组,因此它不会向SecondViewController传递数组的(null)
值。
但是,NSLog(@"Second: %@", [self secondViewControllerArray]);
会输出(null)
。我错过了什么吗?
答案 0 :(得分:2)
在将新视图控制器推入堆栈之前,我不相信您的下载已完成,并且还设置了该视图控制器的数组属性。现在,在您告诉NSURLConnection异步下载数据之后,您正在调用-loadArray。尝试访问数组属性后,此下载将很快完成。
尝试在异步完成块中将调用移动到-loadArray(如下所示)。由于在下载完成时调用此块,因此在按下第二个视图控制器时应该有数据。
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
self.firstViewControllerArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadArray];
});
}];