在循环中阻塞以进行分页

时间:2012-09-01 07:06:12

标签: objective-c block instagram

使用以下代码我试图通过分页来阅读Instagram API内容。在FOR循环中,我打算调用方法loopData来获取带有块的内容,该块在每个循环中都有一个新的页面id。

...

    for (int a = 1; a <= 3; a++)
    {
       NSLog(@"Loop count: %i", a);

       [self loopData];
    }

-(void)loopData 
{
    NSString *next;
    next = [Globals sharedGlobalData].nextMaxId;

    [client getUserMedia:[userTextField stringValue]
                   count:kCount
                   minId:-1
                   maxId:next
                 success:^(NSArray *media) {
                     [textView setString:[media description]];

                     NSLog(@"Next_Max_Id: %@ ", [Globals sharedGlobalData].nextMaxId);

                 }
                 failure:^(NSError *error, NSInteger statusCode) {
                     [self logError:@"media" error:error statusCode:statusCode];
                 }
     ];
}

我的问题是,该块运行了一次,但不是每个循环周期。在for循环结束后块运行。因此,新页面ID无法传递给块。

日志看起来像这样: 循环1 循环2 循环3

通过块读取内容 通过块读取内容 通过块

读取内容

非常感谢您的想法!!

---实现getUserMedia

// Get a user's media
- (void)getUserMedia:(NSString*)userId // Can be 'self' for the current user
               count:(int)count 
               minId:(int)minId // -1 for start
               maxId:(int)maxId // -1 for no upper limit
             success:(void (^)(NSArray* media))success
             failure:(void (^)(NSError* error, NSInteger statusCode))failure {
    // Setup the parameters
    NSMutableDictionary* parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:count], @"count",  nil];
    if (minId > 0) [parameters setObject:[NSNumber numberWithInt:minId] forKey:@"minId"];
    if (maxId > 0) [parameters setObject:[NSNumber numberWithInt:maxId] forKey:@"maxId"];

    // Fire the get request
    [self getPath:[NSString stringWithFormat:@"users/%@/media/recent", userId]
       modelClass:[InstagramMedia class]
       parameters:parameters
       collection:success
           single:nil
          failure:failure];
}

1 个答案:

答案 0 :(得分:0)

传递给此方法的块是异步执行的。客户端启动异步网络请求,并在调用此方法时立即返回。一旦网络请求成功或失败,就会调用您传递给它的其中一个块。这几乎是任何采用块来用于回调的API的标准行为。

我不完全确定你在nextID以及诸如此类的块中想要做什么,但你需要知道:1)块不会在循环内运行2 )他们不会以任何保证的顺序运行。所以无论你想解决什么问题,你都需要牢记这一点。

希望这有帮助,如果您有任何问题,请告诉我。