我的iphone代码带有全局变量不起作用,请指教

时间:2011-10-12 15:02:23

标签: iphone global-variables

我是Objective-c的新手,我在这里搜索并阅读了几篇关于如何创建“全局变量”的帖子但是我无法让它正常工作,到目前为止我可以创建并检查它但是值不是持久存在于另一个视图上,我的全局变量是一个名为“profile”的自定义对象的数组,我希望能够从我的iphone应用程序的任何视图中读取和写入该数组(tabbarapplication delegate);

Helper.h

@interface Helper : NSObject {
    int globalInteger;
    NSMutableArray *profiles;
}

@property (nonatomic, retain) NSMutableArray *profiles;

// message from which our instance is obtained
+ (Helper *)sharedInstance;

Helper.m

#import "Helper.h"


@implementation Helper

@synthesize profiles, globalInteger;

+ (Helper *)sharedInstance
{
    // the instance of this class is stored here
    static Helper *myInstance = nil;

    // check to see if an instance already exists
    if (nil == myInstance) {
        myInstance  = [[[self class] alloc] init];
        // initialize variables here
    }
    // return the instance of this class
    return myInstance;
}

ACertainViewController.m

//Initialize Policies Array
NSMutableArray *profs = [[Helper instance] profiles];
profs = [[NSMutableArray alloc] init];

//Sample Data
Profile *prof1 = [[Profile alloc] init];
prof1.name = @"John";

//add
[profs addObject:prof1];
[[[Helper instance] profiles] addObject:prof1];

在此之后,如果我再次检查全局var“profiles”内容,则返回count == 0; 截至globalInteger var,我甚至不知道如何设置其值以便能够在应用程序中的其他位置读取。 任何帮助深表感谢! 感谢!!!

4 个答案:

答案 0 :(得分:1)

你需要移动"静态助手* myInstance = nil"课外方法。现在,您每次都将其设置为nil,因此每次访问sharedInstance时都会重新分配它。

答案 1 :(得分:0)

您需要分配/初始化profiles数组。试试这个:

// the instance of this class is stored here: thanks @onnoweb for pointing this out
    static Helper *myInstance = nil;
    + (Helper *)sharedInstance
    {
        // check to see if an instance already exists
        if (nil == myInstance) {
            myInstance  = [[[self class] alloc] init];
            // initialize variables here
            profiles=[[NSMutableArray alloc] init];
        }
        // return the instance of this class
        return myInstance;
    }

另请看这里:http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

答案 2 :(得分:0)

在AppDelegate(即MyAppDelegate)类中声明您的NSMutableArray。然后从另一个类(如视图控制器),您可以这样做:

#import "MyAppDelegate.h"

MyAppDelegate *aDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate;
aDelegate.profiles = .... // or do whatever you need to do with the profiles property. 
希望有所帮助。

答案 3 :(得分:0)

“在类方法中访问的实例变量'配置文件”

如果您发布的代码包含注释// initialize variables here,您实际访问的是变量配置文件吗?而是使用myInstance.profiles

“警告:类'Helper'警告的执行不完整:未找到'+ instance'的方法定义”

您没有向我们展示一些代码,或者您发布的代码与您的实际代码不同。您发布的名为'instance'的代码中没有声明或定义的方法,但您尝试调用名为'instance'的方法。有一个名为'sharedInstance'的名称。最有可能在您的真实代码中混淆了名称并声明了'instance'但定义了'sharedInstance'。选择一个名字并坚持下去。

相关问题