【发布时间】:2012-03-06 23:30:09
【问题描述】:
这是我的代码:
我希望能够创建一个全局 NSMutableArray,它可以存储 Budget* 对象,然后可以将其写入 .pList 文件...我只是在学习 pList 是什么,我对如何实现它们...
我哪里错了?
- (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"];
}
edit:我想补充一点,我正在创建 anArray 数组,以便其他视图可以访问它。我知道这可以通过 NSNotification 来完成?还是我应该这样做 appDelegate 类?最终目标是让 anArray 对象填充位于单独视图中的 UITableView。
【问题讨论】:
-
为什么要它是全局的而不是实例变量?
-
不是我反对 plist 而是您是否考虑过其他存储格式,例如 JSON(使用 JSONKit)?如果您打算为其他设备(android)编写此应用程序,JSON 可能是更好的选择。
-
为什么你希望数组在范围内是全局的?还有哪些对象需要访问它?
-
我这样做主要是为了练习应用程序中的持久性概念。但是谢谢@Prowla
-
好吧,我希望能够使用从当前视图创建的对象填充 UITableView。 @skinnyTOD
标签: objective-c ios global-variables