質問

I am trying to save three different objects and then create a joint table with the three of them. I am creating them through a rest api using AFNetworking. My problem is that because all of the objects are in arrays, I would like to create the joint table with the three objects at index 1, 2, 3... To do this I have used to code bellow. The thing is that I need the team to save, the sport to save, and then the period to save, then create the joint table, then move on to the next index path. Currently, it sometimes moves on to the next index path before it saves to joint table, so then I get the wrong values. So, I am looking for a better way to do this, being that the current way is very bad.

Here is the code I am currently using:

-(void)saveSportTeam {

    for (int i=0; i<self.sportsArray.count; i++) {
        id sportObject = self.sportsArray[i];
        id teamObject = self.teamsArray[i];
        id genderObject = self.genderArray[i];

        self.teamString = nil;
        self.sportString = nil;
        self.genderString = nil;

        //
        //Team
        HttpClientSubclass *httpClient = [HttpClientSubclass sharedClient];

        NSDictionary *teamParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                       teamObject, @"team[name]",
                                       nil];
        NSMutableURLRequest *teamRequest = [httpClient requestWithMethod:@"POST"
                                                                       path:@"api/team"
                                                                 parameters:teamParams];
        AFJSONRequestOperation *teamOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:teamRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

            self.teamString = [[NSString alloc] init];
            self.teamString = [JSON valueForKeyPath:@"id"];
            NSLog(@"Here is the team id: %@", self.sportString);


        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            NSLog(@"Request Failure Because %@",[error userInfo]);

            NSDictionary *options = @{
                                      //kCRToastNotificationTypeKey : @(CRToastTypeNavigationBar),
                                      kCRToastNotificationPresentationTypeKey : @(CRToastPresentationTypeCover),
                                      kCRToastTextKey : @"We are having problems, please try again later",
                                      kCRToastTextAlignmentKey : @(NSTextAlignmentCenter),
                                      kCRToastBackgroundColorKey : [UIColor colorWithRed:(255/255.5) green:(59/255.0) blue:(48/255.0) alpha:1.0],//[UIColor redColor], [UIColor colorWithRed:(255/255.5) green:(59/255.0) blue:(48/255.0) alpha:1.0],
                                      kCRToastAnimationInTypeKey : @(CRToastAnimationTypeLinear),
                                      kCRToastAnimationOutTypeKey : @(CRToastAnimationTypeLinear),
                                      kCRToastAnimationInDirectionKey : @(CRToastAnimationDirectionTop),
                                      kCRToastAnimationOutDirectionKey : @(CRToastAnimationDirectionTop)
                                      };
            [CRToastManager showNotificationWithOptions:options
                                        completionBlock:^{
                                            NSLog(@"Completed");
                                        }];
        }];

        [teamOperation start];


        //
        //Sport
        NSDictionary *sportParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                      sportObject, @"sport[name]",
                                      nil];
        NSMutableURLRequest *sportRequest = [httpClient requestWithMethod:@"POST"
                                                                      path:@"api/sport"
                                                                parameters:sportParams];
        AFJSONRequestOperation *sportOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:sportRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

            self.sportString = [[NSString alloc] init];
            self.sportString = [JSON valueForKeyPath:@"id"];
            NSLog(@"Here is the sport id: %@", self.sportString);


        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            NSLog(@"Request Failure Because %@",[error userInfo]);

            NSDictionary *options = @{
                                      //kCRToastNotificationTypeKey : @(CRToastTypeNavigationBar),
                                      kCRToastNotificationPresentationTypeKey : @(CRToastPresentationTypeCover),
                                      kCRToastTextKey : @"We are having problems, please try again later",
                                      kCRToastTextAlignmentKey : @(NSTextAlignmentCenter),
                                      kCRToastBackgroundColorKey : [UIColor colorWithRed:(255/255.5) green:(59/255.0) blue:(48/255.0) alpha:1.0],//[UIColor redColor], [UIColor colorWithRed:(255/255.5) green:(59/255.0) blue:(48/255.0) alpha:1.0],
                                      kCRToastAnimationInTypeKey : @(CRToastAnimationTypeLinear),
                                      kCRToastAnimationOutTypeKey : @(CRToastAnimationTypeLinear),
                                      kCRToastAnimationInDirectionKey : @(CRToastAnimationDirectionTop),
                                      kCRToastAnimationOutDirectionKey : @(CRToastAnimationDirectionTop)
                                      };
            [CRToastManager showNotificationWithOptions:options
                                        completionBlock:^{
                                            NSLog(@"Completed");
                                        }];
        }];

        [sportOperation start];


        //
        //Gender
        NSDictionary *genderParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                     genderObject, @"gender[name]",
                                     nil];
        NSMutableURLRequest *genderRequest = [httpClient requestWithMethod:@"POST"
                                                                     path:@"api/gender"
                                                               parameters:genderParams];
        AFJSONRequestOperation *genderOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:genderRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

            self.genderString = [[NSString alloc] init];
            self.genderString = [JSON valueForKeyPath:@"id"];
            NSLog(@"Here is the sport id: %@", self.genderString);

            [self createSportTeam];


        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            NSLog(@"Request Failure Because %@",[error userInfo]);

            NSDictionary *options = @{
                                      //kCRToastNotificationTypeKey : @(CRToastTypeNavigationBar),
                                      kCRToastNotificationPresentationTypeKey : @(CRToastPresentationTypeCover),
                                      kCRToastTextKey : @"We are having problems, please try again later",
                                      kCRToastTextAlignmentKey : @(NSTextAlignmentCenter),
                                      kCRToastBackgroundColorKey : [UIColor colorWithRed:(255/255.5) green:(59/255.0) blue:(48/255.0) alpha:1.0],//[UIColor redColor], [UIColor colorWithRed:(255/255.5) green:(59/255.0) blue:(48/255.0) alpha:1.0],
                                      kCRToastAnimationInTypeKey : @(CRToastAnimationTypeLinear),
                                      kCRToastAnimationOutTypeKey : @(CRToastAnimationTypeLinear),
                                      kCRToastAnimationInDirectionKey : @(CRToastAnimationDirectionTop),
                                      kCRToastAnimationOutDirectionKey : @(CRToastAnimationDirectionTop)
                                      };
            [CRToastManager showNotificationWithOptions:options
                                        completionBlock:^{
                                            NSLog(@"Completed");
                                        }];
        }];

        [genderOperation start];

    }
    [self saveGrade];
}
役に立ちましたか?

解決

The way to do four things in a row with blocks is to either nest, but this will make for some awful source:

[doThing0:^(id result0) {
    [doThing1:^(id result1) {
        // etc

It was hard to look at your code without all that nesting, so this would be no good. What I prefer instead is making a todo list. The three objects that will be joined can be saved independently, so you could do something like this (pseudo code):

- (void)doRequests:(NSArray *)requests whenDone:(void (^)(NSArray *)done {

    NSMutableArray *todoList = [requests mutableCopy];
    NSMutableArray *results = [NSMutableArray array];

    for (NSMutableURLRequest *request in requests) {
        [AFJSONRequestOperation  JSONRequestOperationWithRequest:sportRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        if (JSON) [results addObject:JSON];
        [todoList removeObject:request];
        if (!todoList.count) {
            done(results);
        }
    }
}

Now you can build all three requests using the code you posted. Instead of running them right away, put the requests in an array. Then...

[self doRequests:@[teamRequest, genderRequest, whateverRequest] whenDone:^(NSArray *results) {
    // if the results array looks good, here you can post to the fourth table.
}];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top