我有以下问题。我有两个操纵信息的类,但它们完全断开连接,即我无法到达另一个类。
我需要两个类都使用某个值。例如,类 A 设置值 foo = A,类 B 需要能够读取该值并将 foo 设为 nil。
我考虑过在主应用程序委托(delegate)中创建变量,但不知道如何创建。
想法?!!
最佳答案
全局变量通常是个坏主意。根据您的描述,我认为您可以使用 KVO通知 B 类“foo”的变化。
但是如果你确实需要一个全局变量,你可以这样做:
@interface YourAppDelegate : NSObject <UIApplicationDelegate> {
}
@property (nonatomic) NSString *foo;
@end
@implementation YourAppDelegate
@synthesize foo;
...
@end
@implementation ClassA
...
- (void)someMethod {
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.foo = @"NewValueOfFoo";
}
...
@end
@implementation ClassB
...
- (void)otherMethod {
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"Value of foo: %@", appDelegate.foo); //This will print: "Value of foo: NewValueOfFoo"
}
...
@end
关于iphone - 需要在objective-c中定义一个 "modifiable"全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5524898/