Search code examples
objective-cblock

pass parameter in objective-c block


My program:

- (void)getPostPraiseListWithSessionId:(NSString *)sid withPostId:(NSString *)postId withPageNo:(int)pageNo completeBlock:(void (^)(NSError *))complete{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{
                                 @"sid":sid,
                                 @"post_id":postId,
                                 @"pageNo":[[NSNumber alloc] initWithInt:pageNo],
                                 };
    [manager POST:[NSString stringWithFormat:@"%@%@",K_BASE_URL,K_GET_POST_PRAISE_LIST_URL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        if([[responseObject objectForKey:@"state"] intValue] == 0){
            NSError *error = [NSError new];
            NSArray *postPraiseList = [MTLJSONAdapter modelOfClass:MSMPostPraiseInfo.class fromJSONDictionary:[responseObject objectForKey:@"data"] error:&error];
            complete(error);
        }else{
            NSError *error = [[NSError alloc] initWithDomain:MSMNETWORK_ERROR_DOMAIN code:[[responseObject objectForKey:@"state"] intValue] userInfo:@{@"message":[responseObject objectForKey:@"message"]}];
            complete(error);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        complete(error);
    }];

}

I have some questions.I wanna pass one parameter to the block named completeBlock,but I don't know what type of the parameter should I use.Should I use the weak type or the strong type?Whatever the type is weak or strong,please tell me the reason.


Solution

  • Rob explained it a lot better, but long story short you use weak when you don't care much about the object being valid, allowing it to be dealloced before your block use it. strong should be used when the object must be valid (and in memory) to be used inside your block.

    Also, here are some minor improvements you could do (which not really related to your question):

    • [[NSNumber alloc] initWithInt:pageNo] can be replaced by a simple @(pageNo)
    • If K_BASE_URL and K_GET_POST_PRAISE_LIST_URL are declared in #define as NSString* macros, you don't need to use stringWithFormat:, you can simply use [manager POST: K_BASE_URL K_GET_POST_PRAISE_LIST_URL parameters:(...)]
    • In this case, your NSError *error = [NSError new]; would probably better off as NSError *error = nil;, but it depends on what that method of MTLJSONAdapter does.