【问题标题】:How to initialize the NSArray in ARC?如何在 ARC 中初始化 NSArray?
【发布时间】:2012-12-23 00:36:55
【问题描述】:

我尝试初始化数组:

在.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 会显示正确的值。但是在点击事件之后它是空的并抛出 EXEC_BAD_ACCESS 错误。

提前感谢您的帮助

【问题讨论】:

  • 我没找到你。你能再解释一下吗?
  • 显示arrList的初始化

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


【解决方案1】:

嗯,看起来不错。那么有几个问题:

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

没有真正的理由认为 arc 应该清除变量。你对它设置了强引用还是弱引用?如果你在变量上使用self.,你应该有:

@property (nonatomic, strong) NSArray *accounts;

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

@synthesize accounts;

在 .m 文件中。

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

【讨论】:

  • 嘿,是的,我正在我的 viewDidload 上初始化数组,并且我已将属性定义为(非原子,保留)。我会更新我的代码
  • 出于好奇,尝试使用self.accounts = [arrList copy]; 看看是否有任何变化?
  • xCode 给你什么错误?是说当您尝试访问该数组时该数组中没有任何数据,还是给您带来了其他错误?
  • 您对账户存储的定义在哪里? acAccountStore?也将其设为@property。数组中的对象可能指向它。如果它被释放,那么这些对象指向的是空内存。
【解决方案2】:

更新:

也为您的帐户商店创建一个属性。我最近遇到了这个确切的问题,这解决了它。

@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]);
    }
 }

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 2012-02-17
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多