0

私はまた戻ってきました。これがその日の2番目の質問になります。

とにかく、私はNSJSONSerialization自分のWebサイトからのデータを解析するために使用しています。データは配列形式なので、を使用してNSMutableArrayいます。問題は、別のViewControllerから保存されているデータにアクセスできないこと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)。私は何かが足りないのですか?

4

1 に答える 1

2

新しいView Controllerをスタックにプッシュし、そのView Controllerの配列プロパティも設定する前に、ダウンロードが完了するとは思いません。現在、NSURLConnection に非同期でデータをダウンロードするように指示した直後に -loadArray を呼び出しています。このダウンロードは、配列のプロパティにアクセスしようとした後、しばらくして終了します。

-loadArray への呼び出しを非同期完了ブロック内に移動してみてください (以下を参照)。このブロックはダウンロードが完了すると呼び出されるため、2 番目のビュー コントローラーをプッシュするときにデータを取得する必要があります。

[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];

        });
}];
于 2013-02-02T18:30:47.323 に答える