目标
只有当变量更改了值时,我才需要我的应用将变量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!")
})
}
问题
一旦变量改变了值,我似乎无法传递变量。我怎么能这样做?
答案 0 :(得分:7)
您应该使用委托协议。有关更多信息,请查看this文档。
在protocol
语句之后的secondClass
中设置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
。
答案 1 :(得分:2)
编程的最佳方法是使用NSNotification。在第二个viewcontroller中添加一个观察者来监听此变量值的变化。在第一个viewcontroller中,每当此变量更改值时,向第二个viewcontroller正在侦听的观察者发送通知。
您必须使用“userInfo”变体并传递包含myVariable值的NSDictionary对象:
NSDictionary* userInfo = @{@"myVariable": @(myVariable)};
NSNotificationCenter *notifying = [NSNotificationCenter defaultCenter];
[notifying postNotificationName:@"myVariableNotification" object:self userInfo:userInfo];
在第二个调用通知中心方法的viewcontroler中 设置通知及其调用方法如下:
[[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);
}
}