0

iOS 開発は初めてです。iOS 5 で json パーサーを使用して画像を解析すると、アプリが遅くなります。この問題を解決するために誰か助けてください。

-(NSDictionary *)Getdata
{
    NSString  *urlString = [NSString stringWithFormat:@"url link"];
    urlString = [urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlString];
    NSData* data = [NSData dataWithContentsOfURL:url];
    NSError* error;
    NSDictionary* json;
    if (data) {
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        NSLog(@"json...%@",json);
    }

    if (error) {
        NSLog(@"error is %@", [error localizedDescription]);

        // Handle Error and return
        //    return;
    }

    return json;
}
4

2 に答える 2

0

問題の説明はまったく役に立ちません。アプリのすべてが遅いのか、それとも特定の操作だけなのか、私にはわかりません。遅いアクションを経験してから再び速くなる場合、またはゆっくりと実行し続ける場合。

いずれにせよ、一般的なルールは、回答の解析を含むすべてのネットワーク通信を別のスレッドで実行することです。つまり、ユーザー インターフェイスの管理を担当するメイン スレッドでは実行しません。そうすれば、アプリの応答性が維持され、高速に見えます。

画像を個別にダウンロードできる場合は、すでに結果を表示して、画像が表示される場所にプレースホルダーを配置できます。後で画像を受け取ったら、プレースホルダーを削除してそこに画像を配置します。

于 2012-11-08T12:25:28.917 に答える
0

この行はおそらく犯人です。

NSData* data = [NSData dataWithContentsOfURL:url];

メイン スレッドでこれを呼び出している場合 (スレッドについてまったく言及していないため、そうであると思われます)、すべてがブロックされ、サーバーが応答するまで待機します。

これは、ユーザーにとって非常に悪い経験です:)

このすべてをバックグラウンド スレッドで実行し、完了したらメイン スレッドに通知する必要があります。これを行う方法はいくつかありますが (NSOperation など)、最も簡単なのは次のとおりです。

// Instead of calling 'GetData', do this instead
[self performSelectorOnBackgroundThread:@selector(GetData) withObject:nil];


// You can't return anything from this because it's going to be run in the background
-(void)GetData {
    ...
    ...

    // Instead of 'return json', you need to pass it back to the main thread
    [self performSelectorOnMainThread:@selector(GotData:) withObject:json waitUntilDone:NO];
}


// This gets run on the main thread with the JSON that's been got and parsed in the background
- (void)GotData:(NSDictionary *)json {
    // I don't know what you were doing with your JSON but you should do it here :)
}
于 2012-11-08T12:33:36.200 に答える