PrepareForSegue mystery

前端 未结 3 1819
暖寄归人
暖寄归人 2021-01-28 13:47

I\'ve got a prepareForSegue method in two different VCs. One uses an if statement, while the other is intended to use a switch. The code is virtually i

相关标签:
3条回答
  • 2021-01-28 14:30

    To solve the second error, try adding braces in your switch-case to define a context to the variables:

    -(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
        [SearchSpecs MR_truncateAllInContext:localContext];
        [localContext MR_saveToPersistentStoreAndWait];
    
        switch ([sender tag])
        {
            case aVsAButton_tag:
                {
                    UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
                    AvsAViewController *aVSaVC = (AvsAViewController *)navController.topViewController;
                    aVSaVC.delegate = self;
                    SearchSpecs *thisSpec = (SearchSpecs *)[SearchSpecs MR_createInContext:localContext];
                    aVSaVC.currentSpec = thisSpec;
                }
                break;
    
            default:
                break;
        }
    
    }
    
    0 讨论(0)
  • 2021-01-28 14:30

    There are two separate problems here.

    You can declare a variable in C/Objective-C in a switch-statement (without the need for an additional { ... } scope), but not immediately following a label. To solve this problem it is sufficient to insert a semicolon after the label:

    switch (i) {
        case 0: ;
            int i;
            // ...
            break;
    
        default:
            break;
    }
    

    Only if you declare Objective-C objects and compile with ARC, then you have to introduce an additional scope:

    switch (i) {
        case 0: {
            NSObject *obj;
            // ...
            } break;
    
        default:
            break;
    }
    

    The reason is that the ARC compiler needs to know the precise lifetime of the object.

    0 讨论(0)
  • 2021-01-28 14:39

    In C/Objective-C, you cannot declare variables in a switch statement like that. If you want to declare variables for use in a specific case of a switch statement, you can put all the code for that case in a statement block:

    switch ([sender tag])
    {
        case aVsAButton_tag:
        {
            UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
            AvsAViewController *aVSaVC = (AvsAViewController *)navController.topViewController;
            aVSaVC.delegate = self;
            SearchSpecs *thisSpec = (SearchSpecs *)[SearchSpecs MR_createInContext:localContext];
            aVSaVC.currentSpec = thisSpec;
        }
            break;
    
        default:
            break;
    }
    
    0 讨论(0)
提交回复
热议问题