Iphone 从数组中获取随机对象,然后将其从数组中移除。苹果手机
我对数组有问题,我想从数组中随机选取一个对象, 然后删除它并删除“if”语句中指定的其他对象 我所做的 在Iphone 从数组中获取随机对象,然后将其从数组中移除。苹果手机,iphone,arrays,object,random,sdk,Iphone,Arrays,Object,Random,Sdk,我对数组有问题,我想从数组中随机选取一个对象, 然后删除它并删除“if”语句中指定的其他对象 我所做的 在 NSMutableArray *squares; int s; NSString *randomN; 接下来,在.m 创建新阵列: -(void) array{ squares = [[NSMutableArray alloc] arrayWithObjects: @"a", @"b", @"c", nil]; } 然后选择一个随机对象,如果满足“if”属性,则从数组中移除该对
NSMutableArray *squares;
int s;
NSString *randomN;
接下来,在.m
创建新阵列:
-(void) array{
squares = [[NSMutableArray alloc] arrayWithObjects: @"a", @"b", @"c", nil];
}
然后选择一个随机对象,如果满足“if”属性,则从数组中移除该对象,再次执行while循环
-(void) start{
s=5;
while (s > 0){
//I even tried it without the next line..
randomN = nil;
//Also tried the next line without ' % [squares count'
randomN = [squares objectAtIndex:arc4random() % [squares count]];
if (randomN == @"a"){
[squares removeObject: @"a"];
[squares removeObject: @"b"];
s = s - 1;
}
if (randomN == @"b"){
[squares removeObject: @"b"];
[squares removeObject: @"c"];
s = s - 1;
}
if (randomN == @"c"){
[squares removeObject: @"c"];
s = s - 1;
}
else {
s=0;
}
}
}
当我运行应用程序时,应用程序停止并在循环开始时退出
您能帮助我吗?我认为问题在于,在创建数组时,您应该使用
initWithObjects
(而不是arrayWithObjects
)
在使用alloc
创建新对象后,应始终使用init*
方法。
arrayWith*
方法是“便利构造函数”,用于autorelease
返回的对象。当您开始使用它时,数组可能已被释放。在objective-c中,您无法使用==
比较字符串,您必须使用isEqual:
方法。@“string”
表示法生成指向内存中其他位置定义的字符串的指针,这些指针可以不同,即使它们指向的数据相同
因此,与其
if (randomN == @"a"){
试一试
他们提出的一些问题可能会让你大吃一惊: 如果要使用便利构造函数初始化已分配的数组,应选择
alloc
/init
对或便利构造函数本身:
[[NSMutableArray alloc] initWithObjects:...]
或:
删除行正在尝试删除字符串文字。虽然数组中包含的字符串实例包含与要删除的字符串相同的值,但它们不是字符串的精确实例。您需要使用[stringVar IsequalString:otherStringVar]
来比较值,而不是它们的引用:
if ([randomN isEqualToString:@"a"])
而不是:
if (randomN == @"a")
if (/* test 1 */) {
}
if (/* test 2 */) {
}
if (/* test 3 */) {
}
else {
// this else only applies to the LAST if!
}
此外,您的else
语句每次都会发出,原因与第二个问题类似。即使您使用了正确的字符串比较,如果您试图只执行这4个代码块中的一个,那么您的逻辑也可能是关闭的。要实现这一点,第一个后的每个if
s都需要一个else
,如下所示:
if (/* test 1 */) {
}
else if (/* test 2 */) {
}
else if (/* test 3 */) {
}
else {
// chained else's make only one block able to execute
}
而不是:
if (randomN == @"a")
if (/* test 1 */) {
}
if (/* test 2 */) {
}
if (/* test 3 */) {
}
else {
// this else only applies to the LAST if!
}
正如亚历克斯所说
squares = [[NSMutableArray alloc] arrayWithObjects: @"a", @"b", @"c", nil];
这条线应该是
squares = [[NSMutableArray alloc] initWithObjects: @"a", @"b", @"c", nil];
或
而且
如果平方是空的,这一行会出现EXC_算术异常(除零)。谢谢大家的回答,我做了你们告诉我的每一件事,现在它工作了:)非常感谢你们的回答,我做了你们告诉我的每一件事,现在它工作了:)非常感谢你们的回答,,你告诉我的每一件事我都做了,现在它起作用了:)非常感谢汉克斯的回答:,你告诉我的每一件事我都做了,现在它起作用了:)非常感谢
squares = [[NSMutableArray arrayWithObjects: @"a", @"b", @"c", nil] retain];
randomN = [squares objectAtIndex:arc4random() % [squares count]];