2011-06-26 44 views
0

我有下面的代碼問題的NSArray

@interface TestYourInfoViewController : UIViewController { 
IBOutlet UIImageView * questionImage; 
NSArray *historyQuestions; 
int questionHistoryNo; 

} 
@property(nonatomic,retain) UIImageView * questionImage; 

@property(nonatomic,retain) NSArray *historyQuestions; 
@property int questionHistoryNo; 
-(IBAction)solution:(id)sender; 

@end 




    - (void)viewDidLoad 
{ 
    NSArray* array = [[NSArray alloc]init]; 
    historyQuestions = array; 
    historyQuestions=UmRandomOrder(49, 1, 0); 



    questionImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"h%@.jpg",[self.historyQuestions objectAtIndex:0]]]; 
    [array release]; 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib. 
} 


-(IBAction)solution:(id)sender{ 

    questionHistoryNo= questionHistoryNo+1; 
    questionImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"h%@.jpg",[self.historyQuestions objectAtIndex:questionHistoryNo]]]; 


} 

當我按下操作按鈕,這讓我異常的行[self.historyQuestions objectAtIndex:questionHistoryNo]

我認爲這個問題是在nsarray莫名其妙,但我不知道它是什麼..例外是 任何人都可以幫助我..

+1

問題歷史不是來自哪裏?爲什麼在使用前添加1?也許你不應該(因爲數組是0索引的)。 – jtbandes

+1

錯誤消息可能實際上非常有用。 – Eiko

+0

檢查陣列中有多少物體?你可能出界了嗎? – dasdom

回答

2

其實DarkDust有它正確的:UMRandomOrder的源代碼顯示它正確地返回一個autorelease NSMutableArray。所以,只是改變了前三行的viewDidLoad中從:

NSArray* array = [[NSArray alloc]init]; 
historyQuestions = array; 
historyQuestions=UmRandomOrder(49, 1, 0); 

只是:

self.historyQuestions=UmRandomOrder(49, 1, 0); 

而且你會沒事的。

具體來說,不需要爲要寫入的數組分配/ init/assign一個數組,並且通過使用屬性setter(self.historyQuestions =),您將自動進行適當的保留,如以及避免潛在的內存泄漏。這也解釋了爲什麼它在viewDidLoad(自動發佈的UmRandomOrder仍然有效)中工作,但不在動作按鈕中(它已經被釋放)。

+0

感謝它的工作..其實我需要了解什麼之間的這個詞(自我)稱之爲和沒有它之間的deffrence因爲我認爲這是所有問題在這裏 –