Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable from a class to another?

Tags:

ios

swift

I need my app to pass the value of a variable myVariable from a class firstClass to another secondClass only when the variable changed its value. To do so, I thought of using the willSet property. Though, in Swift, you can't use it after the declaration of the variable.

class firstClass: NSObject {
    var myVariable = 0

    func myFunction {
       myVariable = 5
    }
}

class secondClass: NSObject {
    var otherClass = firstClass()
    // How do I retrive the value of the variable right after its value changed?
} 

I also thought of adding a NSNotification, but that wouldn't help because it doesn't pass a value. NSNotification only alerts about its changes.

 let myVariableNotification = NSNotification(name: "myVariableNotification", object: nil)

 class firstClass: NSObject {
    var myVariable = 0

    func myFunction {
       myVariable = 5 
       notificationCenter.postNotification(myVariableNotification)
    }
}

class secondClass: NSObject {
    var otherClass = firstClass()
       NSNotificationCenter.defaultCenter().addObserverForName("myVariableNotification", 
         object: nil, 
         queue: NSOperationQueue.mainQueue()
         usingBlock: { notification in
         println("The variable has been updated!")
       })
}

I seem to find no way to pass a variable once that variable changed its value. How can I do that?

like image 973
Cesare Avatar asked Apr 20 '15 17:04

Cesare


People also ask

How do you use a variable from another class in C++?

You can't access other classes private variables. You can access only variables and methods that are declared public. You can not access to "private", but it is possible with "protected"! Maybe this can help you.

How do you pass a class value?

Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.


2 Answers

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.

like image 170
Fengson Avatar answered Oct 19 '22 12:10

Fengson


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);
        }
}
like image 39
Arun Gupta Avatar answered Oct 19 '22 14:10

Arun Gupta