سؤال

i have two views MainView and MainInvoicing

from MainView i am sending a int type variable value to MainInvoicing

this is my code

in MainInvoicing.h file i declared int type var

@property (nonatomic, assign) int myChoice;

in MainView.m file on a button click i am calling the MainInvoicing as

MainInvoicing *invoicing = [[MainInvoicing alloc] initWithNibName:@"Invoicing" bundle:nil];
[self presentViewController:invoicing animated:YES completion:nil];
invoicing.myChoice = 1;

from this my MainInvoicing is called perfectly, but myChoice is equal to zero '0'. while it should be '1'

i am receiving this value in MainInvoicing.m as

- (void)viewDidLoad
{
[super viewDidLoad];
[self Start];
}

and the start method is

- (void) Start
{
switch (myChoice)
{
    case 1:
        NSLog(@"value is %d",myChoice);
        break;
    case 2:
        NSLog(@"value is %d",myChoice);
        break;
    default:
        NSLog(@"Oooopppss...%d",myChoice);
        break;
}
}

i am always on default part ….

where am i wrong or any suggestion to get the right value … please help…

هل كانت مفيدة؟

المحلول

You should assign value before you present view controller:

 MainInvoicing *invoicing = [[MainInvoicing alloc] initWithNibName:@"Invoicing" bundle:nil];
invoicing.myChoice = 1;
[self presentViewController:invoicing animated:YES completion:nil];

نصائح أخرى

As Greg said in his comment, it's all about order of code. If you look at your code you should see the order in which it is called.

MainInvoicing *invoicing = [[MainInvoicing alloc] initWithNibName:@"Invoicing" bundle:nil];
[self presentViewController:invoicing animated:YES completion:nil];
    [self Start];
        switch (myChoice)
        {
            case 1:
                NSLog(@"value is %d",myChoice);
                break;
            case 2:
                NSLog(@"value is %d",myChoice);
                break;
            default:
                NSLog(@"Oooopppss...%d",myChoice);
                break;
        }
invoicing.myChoice = 1;

So you are trying to access the myChoice variable before you set it, which is why you are getting 0 instead of 1.

With all of that said, there is a possibility of your code working as it is written since the viewDidLoad function is not always called serially. But you should not expect it to always work and you should initialize variables before you call code that could use them immediately.

Accept Greg's answer, I was just adding a bit of explanation to the problem.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top