working on xcode I realized that if I create a non-void method, I call it from a class / method, the result is processed optimally only if the action is immediate. I tried to do a test by inserting a delay and I realized that it no longer works.
I will write down here the example that I created:
Class A
//--------------------CLASS A
- (void)viewDidLoad {
[super viewDidLoad];
i = 0;
Class *classB = [[Class alloc] init];
i = [classB method1];
[self performSelector:@selector(method3) withObject:NULL afterDelay:1.8];
}
-(void)method3 {
NSLog(@"i = %i",i); // i = 0
}
Class B
//--------------------CLASS B
-(int)method1 {
[self performSelector:@selector(method2) withObject:NULL afterDelay:1];
return a;
}
-(void)method2 {
a = 800;
}
Obviously my problem is not something so trivial but I tried to make it easy to get an answer as thoroughly as possible, I was advised to use modal methods but I don’t think that’s the solution I was looking for.
What could I do to solve this?!
What you really need is a better understanding of asynchronous methods. In your
method1, the variableais never altered — all you are doing is schedulingmethod2to be called in the future and then returning the current state of variablea.In Objective-C, there are a few different ways you can solve this problem. People most commonly use
protocolsanddelegatesto solve this issue. Here is a basic intro to protocols and delegates. Basically, you would want your class A object to be a delegate of your class B object. You could also use NSNotifications or blocks, although you should probably understand the usage of protocols and delegates (they are very important in Objective-C) before moving on to notifications and blocks.