我正在用Obj-c做一点自学,并且有兴趣制作闪存卡应用程序。我有一个NSArray,对象中有5个图像。当用户按下前进按钮时,我试图让我的UIImageView显示数组中的下一个图像。我从我的数组中获取图像的行上获得了线程1:EXC_BAD_ACCESS(Code = 2,address = 0x0)。这是我当前的标题和实现文件。
@interface WhoAmIViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIImageView *flashcardviewer;
@property (strong, nonatomic) NSArray *aryFlashcards;
@property (nonatomic) NSUInteger *int_counter;
@end
@implementation WhoAmIViewController
@synthesize aryFlashcards;
@synthesize flashcardviewer;
@synthesize int_counter;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
aryFlashcards = [NSArray arrayWithObjects:
[UIImage imageNamed:@"shot_1"],
[UIImage imageNamed:@"shot_2"],
[UIImage imageNamed:@"shot_3"],
[UIImage imageNamed:@"shot_4"],
[UIImage imageNamed:@"shot_5"],
nil];
int_counter = 0;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//back button
- (IBAction)btn_back:(UIButton *)sender {
}
//forward button
- (IBAction)btn_forward:(UIButton *)sender
{
flashcardviewer = [[UIImageView alloc]init];
UIImage *flashcard_next = [UIImage imageNamed:[aryFlashcards objectAtIndex:*(int_counter)]]; //This is where Xcode throws me an error.
flashcardviewer.image = flashcard_next;
int_counter++;
}
//random button
- (IBAction)btn_random:(UIButton *)sender
{
}
请尝试以下代码:
//Declare int_counter like this
@property (nonatomic) NSUInteger int_counter;
//Set btn_forward: this way
- (IBAction)btn_forward:(UIButton *)sender
{
//Avoid possible app crash with a if condition
if (int_counter < flashcard_next.count) {
UIImage *flashcard_next = [aryFlashcards objectAtIndex:int_counter];
flashcardviewer.image = flashcard_next;
int_counter++;
} else {
NSLog (@"No more cards");
}
}
您可以了解更多关于NSInteger
here的信息。
你使int_counter成为指针而不是NSInteger。尝试
@property (nonatomic) NSUInteger int_counter;
和
UIImage *flashcard_next = [aryFlashcards objectAtIndex:int_counter];
你的问题就在这条线上:
UIImage *flashcard_next = [UIImage imageNamed:[aryFlashcards objectAtIndex:*(int_counter)]];
你正在创建一个UIImage
对象,并在它期待一个UIImage
时将另一个NSString
传递给该方法。将其更改为:
UIImage *flashcard_next = [aryFlashcards objectAtIndex:int_counter];
并且如在另一个答案中提到的,删除指向int_counter
的指针。
您的iVar aryFlashcards已在viewDidLoad方法中使用5个图像进行实例化。在你的btn_forward方法实现中你应该替换
UIImage *flashcard_next = [UIImage imageNamed:[aryFlashcards objectAtIndex:*(int_counter)]];
使用以下提供的*(int_counter)小于aryFlashCards大小,在您的示例中看起来为5,否则您的应用将抛出超出绑定的异常。
UIImage *flashcard_next = [aryFlashcards objectAtIndex:*(int_counter)];