将对象添加到NSMutablearray无法正常工作

时间:2012-10-10 13:17:37

标签: objective-c nsmutablearray

我有一种情况,在循环中我试图将对象添加到NSMutableArray。在循环结束时,它显示54个对象(作为示例)被添加到数组中但是当我试图从数组中读取对象时,显然它们彼此完全相同并且相同插入到数组中的最后一个对象。

有人可以帮我解决这个问题。这是我的代码:

int counter=0;

for (int j=0; j<rows; j++) 
{      
     Product *product ;
     product = [[Product alloc] init];
     int numberr= [product getImageNumber];
     [wineList addObject:product];
     counter = counter + 1;  
}

添加对象后,我正在测试数组的内容,我对数组中的每个项目得到相同的结果

//testing
Product *producttest1 = wineList[1];
int numbertest1= [producttest1 getImageNumber];
Product *producttest2 = wineList[20];
int numbertest2= [producttest2 getImageNumber]; 

这是我所拥有的Product类的定义:

#import "Product.h"
@implementation Product

int imageNumber;
bool isInCase;

-(id) init {
    imageNumber = (arc4random() % 11) + 1;

    isInCase = false;

    return self;
}

-(int) getImageNumber {

    return imageNumber;
}

-(void) setImageNumber:(int) number {

    imageNumber = number;
    }

2 个答案:

答案 0 :(得分:1)

您的-init方法永远不会初始化您的课程。拨打[super init]

-(id)init {
    self = [super init];

    if (self) {
        imageNumber = (arc4random() % 11) + 1;
        isInCase = false;
    }

    return self;
}

答案 1 :(得分:0)

你的代码应该是这样的,

int counter=0;
for (int j=0; j < rows; j++) 
{      
     Product *product = [[Product alloc] init]; // Added variable declaration inside.
     int numberr= [product getImageNumber];
     [wineList addObject:product];
     [product release];                         // Added release for product
     counter = counter + 1;  

}