【问题标题】:need to define a "modifiable" global variable in objective-c需要在objective-c中定义一个“可修改”的全局变量
【发布时间】:2011-04-02 18:01:15
【问题描述】:

我有以下问题。我有两个处理信息的类,但它们完全断开连接,即我无法访问另一个类。

我需要两个类都使用某个值。例如,A 类设置值 foo = A,B 类需要能够读取该值并将 foo 设置为 nil。

我想过在主应用程序委托中创建变量,但不知道如何。

想法?!!

【问题讨论】:

    标签: iphone objective-c cocoa global-variables


    【解决方案1】:

    全局变量通常是个坏主意。根据您的描述,我认为您可以使用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
    

    【讨论】:

    • GojaN是否需要在 app delegate .m 中合成 foo?
    • GajaN,你没有在类数据区声明 NSString *foo ,可以吗?
    • @leo 从Objective-C 2.0 开始工作。在以前的版本中,编译器会抱怨
    【解决方案2】:

    我不确定您所说的“完全断开连接”是什么意思。根据您要执行的操作,您可以使用 NSUserDefaults

    http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

    或 NSNotifications

    http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNotification_Class/Reference/Reference.html

    如果A类不需要知道B类,你也可以考虑委托。

    【讨论】:

      【解决方案3】:

      他为什么不能这样做?

      A.向您的项目添加 2 个新文件:GlobalValues.hGloblaValues.m

      B.打开GlobalValues.h,并声明所有需要的变量。

      extern NSString *MyServiceName; // name of the 'service':

      C.打开GlobalValues.m,并通过导入GlobalValues.h来启动新文件,并为你在头文件中声明的变量赋值:

      #import "GlobalValues.h"

      NSString *MyServiceName = @"MyService is called THIS";

      D.在需要使用这些变量的类的实现文件中,您可以将 - 放在最开头:

      #import "GlobalValues.h"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-07
        • 1970-01-01
        相关资源
        最近更新 更多