我正在尝试创建一个图像类的数组时遇到错误
由于未捕获的异常'NSRangeException'而终止应用程序,原因:'*** - [__ NSArrayI objectAtIndex:]:index 205003599 beyond bounds [0 .. 5]”我正在尝试创建一个图像类的数组时遇到错误
我写在.h文件中的代码
#import <Foundation/Foundation.h>
@interface image : NSObject
@property(strong,nonatomic) NSArray *myimage;
-(image *) randomimage;
@end
我实现它的.m文件
#import "image.h"
#import <UIKit/UIKit.h>
@implementation image
- (instancetype)init
{
self = [super init];
if (self) {
_myimage =[[NSArray alloc]initWithObjects:
[UIImage imageNamed:@"Earth.jpg"],
[UIImage imageNamed:@"Jupiter.jpg"],
[UIImage imageNamed:@"Orion.jpg"],
[UIImage imageNamed:@"Saturn.jpg"],
[UIImage imageNamed:@"Venus.jpg"],
[UIImage imageNamed:@"Mars.jpg"],
nil];
}
return self;
}
-(image *) randomimage{
int randimage=arc4random_uniform((int)self.myimage);
return [self.myimage objectAtIndexedSubscript:randimage];
}
@end
你期望什么?看看你的代码:
int randimage=arc4random_uniform((int)self.myimage);
return [self.myimage objectAtIndexedSubscript:randimage];
arc4random_uniform
可以在0和它的参数之间的任何回报。参数是self.myimage
- 一个对象。它的值不是一个整数,但是你迫使它成为一个整数。因此你得到的是这个对象的内存位置,它可以是任何数字。所以你最终得到了一个巨大的数字,超出了数组中元素的实际数量。你的意思可能是self.myimage.count
,不是吗?
当你的意思只是'objectAtIndex:'时,也不要调用'objectAtIndexedSubscript:'。这太愚蠢了。 – matt 2015-04-02 17:29:16
谢谢你们..它的作品self.myimage.count – 2015-04-02 18:08:54
你会得到一个超过图像数组边界的索引的随机整数。限制随机数生成器仅生成0-5之间的数字,因为数组中只有6个图像。 – Zack 2015-04-02 17:26:12