我又回来了,这是我今天的第二个问题。
无论如何,我正在使用 NSJSONSerialization
来解析来 self 网站的数据。数据采用数组格式,因此我使用的是 NSMutableArray
。问题是,我无法从不同的 View Controller 访问存储在 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];
}
第二.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@property (nonatomic, strong) NSMutableArray *secondViewControllerArray;
@end
第二.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"Second: %@", [self secondViewControllerArray]);
}
输出
NSLog(@"First: %@",array);
将输出数组,因此它不会将 (null)
值传递给 SecondViewController数组。
但是,NSLog(@"Second: %@", [self secondViewControllerArray]);
将输出 (null)
。我错过了什么吗?
最佳答案
在您将新 View Controller 插入堆栈并设置该 View Controller 的数组属性之前,我认为您的下载尚未完成。现在,您在告诉 NSURLConnection 异步下载数据后立即调用 -loadArray。此下载将在您尝试访问数组属性后很长时间内完成。
尝试在异步完成 block 中移动对 -loadArray 的调用(如下所示)。由于这个 block 在下载完成时被调用,所以当你推送第二个 View Controller 时你应该有你的数据。
[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];
});
}];
关于iphone - 从不同的 View Controller 访问来自 NSJSONSerialization 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14664989/