Mohamed Emad Hegab
Mohamed Emad Hegab

Reputation: 2675

Problem With NSArray

i have the following code

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


}

when i press the action button it gives me exception in the line [self.historyQuestions objectAtIndex:questionHistoryNo]

i believe the problem is in the nsarray somehow but i don't know what is it.. the exception is can anyone help me ..

Upvotes: 0

Views: 128

Answers (1)

mackworth
mackworth

Reputation: 5953

Actually DarkDust has it correct: the source code for UMRandomOrder shows that it properly returns an autorelease NSMutableArray. So, just change the first three lines of your viewDidLoad from:

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

to just:

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

And you'll be fine.

To be specific, there's no need to alloc/init/assign an array you're about to write over, and by using the property setter (self.historyQuestions = ), you'll automatically do a proper retain, as well as avoiding a potential memory leak. That also explains why it works in viewDidLoad (the autoreleased UmRandomOrder is still valid), but not in the action button (it has since been released).

Upvotes: 2

Related Questions