【问题标题】:How to pass a variable from a class to another?如何将变量从一个类传递给另一个?
【发布时间】:2015-04-20 17:12:28
【问题描述】:

仅当变量更改其值时,我需要我的应用程序将变量 myVariable 的值从类 firstClass 传递给另一个 secondClass。为此,我想到了使用 willSet 属性。但是,在 Swift 中,您不能在声明变量后使用它。

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?
} 

我也想过添加一个NSNotification,但这无济于事,因为它没有传递值。 NSNotification 仅提醒其更改。

 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!")
       })
}

一旦变量改变了它的值,我似乎找不到传递变量的方法。我该怎么做?

【问题讨论】:

  • 您想在从第一个视图控制器导航到第二个视图控制器时传递值,还是仅在该变量的值发生变化时传递值?
  • 感谢您的评论!仅当myVariable 更改其值时。谢谢!

标签: ios swift


【解决方案1】:

您应该使用委托协议。有关更多信息,请查看this 文档。

secondClass 中设置protocol,就在import 语句之后,如下所示:

protocol InformingDelegate {
    func valueChanged() -> CGFloat
}

在同一个secondClass里面创建一个delegate变量(有人建议应该标记为weak):

var delegate: InformingDelegate?

然后,创建一些方法来访问更改后的值。您可以将其分配给value,例如:

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

这是secondClass。现在转到firstClass
这里只需要在类定义后面加上InformingDelegate就可以符合协议了,像这样:

class firstClass: UIViewController, InformingDelegate {
    ...
}

然后,通过创建另一个类的实例并将自己设置为委托来通知编译器您将成为另一个类的委托:

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!

最后一件事是通过实现它的方法来真正符合协议:

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

这会将myVariable 值(在本例中为5)分配给另一个类中的value

【讨论】:

  • 非常感谢!我应该把var delegate: InformingDelegate?放在一等还是二等?
  • 您创建一个协议,并在类中创建一个 var "delegate" 来检索该值。然后,通过将 InformingDelegate 分配给类定义,将另一个类(将实现方法并设置值的类)设置为该协议的委托。
  • 谢谢! protocols 应该放在哪里?课外?
  • 协议定义应该放在类定义之上,紧跟在import语句之后:)
  • 现在正在处理它。我非常感谢你为写这篇文章所付出的努力:-) 谢谢!
【解决方案2】:

最好的编程方式是使用 NSNotification。在你的第二个视图控制器中添加一个观察者来监听这个变量值的变化。在第一个视图控制器中,每当此变量更改值时,都会向观察者发布通知,第二个视图控制器正在侦听。

您必须使用“userInfo”变体并传递一个包含 myVariable 值的 NSDictionary 对象:

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

在调用通知中心方法的第二个视图控制器中 设置通知及其调用方法如下:

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

调用方法:

-(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);
        }
}

【讨论】:

  • 感谢您的回答! NSNotification 是否传递值?我使用了它,但它只提醒变量的变化。请检查我编辑的问题。我添加了用于声明和设置NSNotification 的代码。你能显示一些代码吗?谢谢!
  • 该变量是否总是返回整数?
  • 是的,它会的。谢谢。
猜你喜欢
  • 2011-03-15
  • 2019-05-02
  • 2021-07-25
  • 2014-01-03
  • 1970-01-01
  • 2013-02-08
相关资源
最近更新 更多