我有以下代码
@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中,但我不知道它是什么......例外是 任何人都可以帮助我..
答案 0 :(得分:2)
实际上DarkDust的说法是正确的:UMRandomOrder的源代码显示它正确返回了自动释放NSMutableArray。因此,只需更改viewDidLoad的前三行:
NSArray* array = [[NSArray alloc]init];
historyQuestions = array;
historyQuestions=UmRandomOrder(49, 1, 0);
只是:
self.historyQuestions=UmRandomOrder(49, 1, 0);
你会没事的。
具体来说,不需要分配/初始化/分配你要写的数组,并且通过使用属性设置器(self.historyQuestions =),你也可以自动进行适当的保留。避免潜在的内存泄漏。这也解释了为什么它在viewDidLoad中工作(自动释放的UmRandomOrder仍然有效),但不在动作按钮中(它已经被释放)。