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

标签 objective-c ios global-variables

这是我的代码:

我希望能够创建一个全局 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"];
}

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

最佳答案

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

NSMutableArray *anArray = nil;

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

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

如果仅在一种方法中使用,请将其设为“静态”并将其放入该方法中:
- (IBAction)btnCreateBudget:(id)sender 
{
    static NSMutableArray *anArray = nil;
    ...
    if ( anArray == nil )
      anArray = [[NSMutableArray alloc] init]; 
    ...
}

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

关于objective-c - 在哪里为 iOS 应用程序创建全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9593594/

相关文章:

javascript - JS : How to use abbreviations for full named variables?

python - 类中的全局变量共享给其他实例

ios - 自动布局:在不知道高度约束的情况下隐藏 UIView

iOS6 向具有角半径的容器 UIView 添加阴影

ios - 检查日期是否在范围内

ios - FSCalendar 日期未正确对齐

objective-c - 在设备上使用 imageNamed 失败,但在模拟器中有效

每次点击应用程序图标时,iOS 13 应用程序都会请求一个新场景

ios - dispatch_get_main_queue block 中的代码

Java - 监听变量变化