How to pass a variable from a class to another?

You should use delegate protocols. For more information check out this document.

Set up a protocol in the secondClass, right after the import statements, like so:

protocol InformingDelegate {
    func valueChanged() -> CGFloat
}

Inside the same secondClass create a delegate variable (some suggest that it should be marked as weak):

var delegate: InformingDelegate?

Then, create some method in which you will access the changed value. You can assign it to value for example:

func callFromOtherClass() {
    value = self.delegate?.valueChanged()
}

This is it for the secondClass. Now onto the firstClass.
Here you only need to conform to the protocol by adding InformingDelegate after the class definition, like this:

class firstClass: UIViewController, InformingDelegate {
    ...
}

Then, inform the compiler that you are going to be a delegate for the other class by creating its instance, and setting yourself to be the delegate:

var secondVC : secondClass = secondClass()
secondClass.delegate = self
secondClass.callFromOtherClass() // This will call the method in the secondClass  
// which will then ask its delegate to trigger a method valueChanged() -   
// Who is the delegate? Well, your firstClass, so you better implement  
// this method!

The last thing is to actually conform to the protocol by implementing its method:

func valueChanged() -> CGFloat {
    return myVariable // which is 5 in your case (value taken from a question)
}

This will assign myVariable value (5 in this example) to the value in the other class.


Best way to program this would be using NSNotification. Add a observer in your 2nd viewcontroller to listen for change in value of this variable. In 1st viewcontroller whenever this variable changes value post a notification to observer which 2nd viewcontroller is listening to.

You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the value of myVariable:

NSDictionary* userInfo = @{@"myVariable": @(myVariable)};
NSNotificationCenter *notifying = [NSNotificationCenter defaultCenter];
[notifying postNotificationName:@"myVariableNotification" object:self userInfo:userInfo];

In your second viewcontroler which calls your notification center method set the notification and its calling method as below:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeInValue:) name:@"myVariableNotification" object:nil];

Calling method:

-(void) changeInValue:(NSNotification*)notification
{
    if ([notification.name isEqualToString:@"myVariableNotification"])
        {
            NSDictionary* userInfo = notification.userInfo;
            NSNumber* myVariable = (NSNumber*)userInfo[@"myVariable"];
            NSLog (@"Successfully received test notification! %i", myVariable.intValue);
        }
}

Tags:

Ios

Swift