2012-12-23 78 views
0

我試圖初始化數組:如何在ARC中初始化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錯誤。

感謝您的幫助提前

+0

我沒有得到你。你能再解釋一遍嗎? – insomiac

+0

讓我看看arrList的初始化 – CodaFi

回答

0

hm看起來不錯。幾個問題然後:

你在哪裏打電話self.accounts = [NSArray arrayWithArray:arrList]; 我假設你的按鈕被按下之前正在設置數組?

沒有真正的理由說arc應該清除變量。你有沒有強烈地提到它或弱者?如果你對一個變量使用self.,你應該有:

@property (nonatomic, strong) NSArray *accounts; 

或.h文件類似,然後

@synthesize accounts; 
在.m文件

如果你有weak而不是strong那麼ARC可能會清除內存,但它仍然不應該。

+0

嘿是的,我正在初始化我的viewDidload上的數組,並且我已經將propery定義爲(nonatomic,retain)。我會更新我的代碼 – insomiac

+0

出於好奇,嘗試使用'self.accounts = [arrList copy];'看看是否有任何改變? – PaReeOhNos

+0

我試過這個不行。 – insomiac

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