我在哪里为iOS应用程序创建全局变量?

这是我的代码:

我希望能够创建一个全局的NSMutableArray,它可以存储Budget *对象,然后可以将其写入.pList文件……我只是在学习pLists,我对如何实现它们有点模糊。 ..

我在哪里错了?

- (IBAction)btnCreateBudget:(id)sender { Budget *budget = [[Budget alloc] init]; budget.name = self.txtFldBudgetName.text; budget.amount = [self.txtFldBudgetAmount.text intValue]; // Write the data to the pList NSMutableArray *anArray = [[NSMutableArray alloc] init]; // I want this to be a global variable for the entire app. Where do I put this? [anArray addObject:budget]; [anArray writeToFile:[self dataFilePath] atomically:YES]; /* As you can see, below is where I test the code. Unfortunately, every time I run this, I get only 1 element in the array. I'm assuming that this is because everytime the button is pressed, I create a brand new NSMutableArray *anArray. I want that to be global for the entire app. */ int i = 0; for (Budget * b in anArray) { i++; } NSLog(@"There are %d items in anArray",i); } -(NSString *) dataFilePath { NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [path objectAtIndex:0]; return [documentDirectory stringByAppendingPathComponent:@"BudgetData.plist"]; } 

编辑:我想补充说我正在创建一个anArray数组,以便其他视图可以访问它。 我知道这可以通过NSNotification完成吗? 或者我应该这样做appDelegate类? 最终目标是让anArray对象填充位于单独View中的UITableView。

只需将声明放在方法之外而不是在其中。

 NSMutableArray *anArray = nil; - (IBAction)btnCreateBudget:(id)sender { ... if ( anArray == nil ) anArray = [[NSMutableArray alloc] init]; ... } 

如果它仅在一个文件中使用,请将其设置为“静态”,以防止与其他文件发生名称冲突:

  static NSMutableArray *anArray = nil; 

如果它仅在一个方法中使用,则将其设置为“static”并将其放在该方法中:

 - (IBAction)btnCreateBudget:(id)sender { static NSMutableArray *anArray = nil; ... if ( anArray == nil ) anArray = [[NSMutableArray alloc] init]; ... } 

请注意,人们通常对全局变量使用某种命名约定,例如“gArray”,以便轻松地将它们与局部变量,实例变量或方法参数区分开来。

在这种情况下,不需要全局变量。 你可以这样做:

  1. 将旧数据读入可变数组( initWithContentsOfFile:
  2. 将新记录添加到arrays。
  3. 将数组保存到同一文件。

但是代码中的第二个问题是,如果您的Budget类不是属性列表类型(NSString,NSData,NSArray或NSDictionary对象),则writeToFile:将不会成功保存它。

您需要确保您的Budget类调用NSCoder ,然后调用NSCoder initWithCoder:NSCoder decodeWithCoder:方法。 否则, writeToFile:将无法为您的NSObject类工作。

但我离题了。 原始问题的答案应如下。

.h文件中,您需要执行以下操作。

 @interface WhateverClassName : UIViewController { NSMutableArray *anArray; } @property(nonatomic, retain) NSMutableArray *anArray; @end 

然后,你需要确保你@synthesize NSMutableArray这样你就不会得到任何怪异的警告。 这是在.m文件中的@implementation行之后完成的。

然后,在您希望将其分配到内存的函数中,只需执行以下操作即可。

 anArray = [[NSMutableArray alloc] initWithObjects:nil]; 

现在这是一个global变量。 它在某种意义上是global的,它可以从任何function中使用,并且不限于在一个function中使用。

如果您希望整个应用程序或上下文(“全局”)可以访问数据,则可以使用单例。 但是,要小心这样做,并确保它实际上是必要和适当的。 在任何单例实现之前,我建议大量阅读它。 卡特艾伦在这里有一个很好的基本实现。

根据“最终目标是让anArray对象填充位于单独视图中的UITableView”,您不需要向文件,数据库或单例写入任何内容。 只需设置对象。 如Sebastien Peek所述。

如果您希望离线数据存储,请查看sqlite,json,plist等