如何初始化ARC中的NSArray?

时间:2012-12-23 00:36:56

标签: objective-c ios xcode memory-management nsarray

我尝试初始化数组:

在.h文件中

    @property (nonatomic, retain) NSArray *accounts;

在.m文件中:

    @synthesize accounts;

    - (void)viewDidLoad
    {
       [super viewDidLoad];
       NSArray *arrList = [acAccountStore accountsWithAccountType:accountType];  
       // This returns array
       self.accounts = [NSArray arrayWithArray:arrList]; // I tried debug after 
       // this and it gives me data in debugger.  
       // Note array List have 3 data in it.   
       }

现在点击按钮,我点击一个方法:

- (IBAction) ButtonClicked :(id) sender {
      NSLog(@" data : %@",[self.accounts objectAtIndex:0]); // Breaks at this point. 
      //  When i tried with debug it gives me (no Objective-C description available)
}

数组初始化是否正确如果代码不对,请告诉我。

主要关注的是当我在viewDidLoad中进行调试时,self.accounts会显示正确的值。但在执行click事件后,它为空并抛出EXEC_BAD_ACCESS错误。

提前感谢您的帮助

2 个答案:

答案 0 :(得分:0)

hm看起来不错。那么几个问题:

你在哪里打电话给self.accounts = [NSArray arrayWithArray:arrList]; 我假设在按下按钮之前正在设置数组?

没有理由认为弧应该清除变量。你有没有强烈提及它或弱者?如果您对变量使用self.,则应该:

@property (nonatomic, strong) NSArray *accounts;

或类似于.h文件中的内容,然后

@synthesize accounts;
<。>文件中的

如果你有weak而不是strong,那么ARC可能会清除内存,但它仍然不应该。

答案 1 :(得分:0)

<强>更新

也为您的帐户商店创建一个属性。我最近遇到了这个问题并修复了它。

@property (nonatomic, strong) ACAccountStore *accountStore;

原始答案

因为您使用的是ARC,所以您需要从

更改属性声明
@property (nonatomic, retain) NSArray *accounts;

为:

@property (nonatomic, strong) NSArray *accounts;

使用最新的LLVM编译器,您也不需要合成属性。因此,您可以删除@synthesize accounts

您也应该始终使用防御性编码,因此在您的- buttonClicked:方法中,您应该这样做:

- (IBAction)buttonClicked:(id)sender {
    if (self.accounts) {
          NSLog(@"data: %@", [self.accounts objectAtIndex:0]);
    }
}

这可确保指向数组的指针有效。

您还可以通过执行以下操作检查以确保数组中的项目是否存在,然后执行以下操作:

- (IBAction)buttonClicked:(id)sender {
    if (self.accounts.count > 0)
          NSLog(@"data: %@", [self.accounts objectAtIndex:0]);
    }
 }