0

Web サービスがあり、iPhone アプリケーションからこのサービスを定期的に呼び出して、アプリケーションの実行中に 1 分ごとにデータをキャッシュしたいと考えています。

私はNSTimerを使用してこのサービスを呼び出す関数を呼び出しますが、新しい呼び出しを続行する前に、最初の呼び出しが最初の呼び出しからのデータの解析を終了したことは残念です。どうすればそれができますか?

{
 NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
 NSTimer *t = [[NSTimer alloc] initWithFireDate: d
                                      interval: 10
                                        target: self
                                      selector:@selector(calltimer:)
                                      userInfo:nil repeats:YES];

 NSRunLoop *runner = [NSRunLoop currentRunLoop];
 [runner addTimer:t forMode: NSDefaultRunLoopMode];
 [t release];
}

-(void)calltimer :(id)sender
{
    NSLog(@"yessss");

    if(!myQueue)
    {
        myQueue = dispatch_queue_create("supperApp.user1025523.com", NULL);
        dispatch_async(myQueue, ^{
            [self getData]; 
            });
    }    
}

-(void)getData
{
    webserviceCaller* wsCaller = [[webserviceCaller alloc]initWithTarget:self     selector:@selector(parsINVData:)];
    [wsCaller getINventoryData:self.username];
    [wsCaller release];
}

-(void) parsINVData:(InvData*) ret
{
    //save return data in global variable      
}

NSMutableURLRequestを使用して要求パラメーターを開始し、 NSURLConnectionを使用して接続を開始したため、Web サービスへの呼び出しが発生しなかったのはなぜですか。

4

2 に答える 2

2

次のように、クラス レベルのメンバー変数を追加できます。

.h ファイル内

{
    BOOL finishedParsing;
}

- (void) nsTimerFunctionCall
{
    if(!finishedParsing)
    {
        //Either return, or recall this same function after some time
        return;
    }

   [self parseCode];
}

- (void) parseCode
{
    finishedParsing = NO;

    //do long processing function
    //....

    finishedParsing = YES;
}

このようにして、関数への別の呼び出しが処理されている間に解析コードが呼び出されないようにすることができます

于 2012-05-21T18:43:15.930 に答える
1

シリアル キューを使用して、1 つのタスクが次のタスクを確実に待機するようにします。

- (id)init
{
    self = [super init];
    if( !self ) return nil;

    parsing_queue = dispatch_queue_create("superApp.user1025523.com", NULL);

    // etc.

- (void)timerAction: (NSTimer *)tim
{
    // Enqueue the work. Each new block won't run until the 
    // previous one has completed.
    dispatch_async(parsing_queue, ^{
        // Do the work
    });
}

これもバックグラウンドで自動的に行われます。

于 2012-05-21T19:05:02.517 に答える