我主要用Java编程,无法理解为什么这不起作用。我正在尝试在for循环中创建一个临时对象“Judge”。然后我想将该对象添加到一个NSMutableArray,所以最后我有一个数组填充了不同的Judge对象。在循环之后,我遍历数组中的所有对象,它们都是最后一个判断对象。将自定义对象添加到NSMutableArray
NSLog显示在for循环中“JudgeTemp”对象正在分配正确的值。我的猜测是,它不是每次创建一个名为JudgeTemp的新对象,而是引用已经创建的旧JudgeTemp。
NSMutableArray *Judges = [NSMutableArray arrayWithCapacity:30];
for (int i=0; i<[courtinfoarray count]; i++) {
Judge1= [[courtinfoarray objectAtIndex:i] componentsSeparatedByString:@"|"];
Judge *JudgeTemp=[[Judge alloc]init];
[JudgeTemp setName:[Judge1 objectAtIndex:0] picture:[Judge1 objectAtIndex:1] courtroom:[Judge1 objectAtIndex:2] phone:[Judge1 objectAtIndex:3] undergrad:[Judge1 objectAtIndex:4] lawschool:[Judge1 objectAtIndex:5] opdasa:[Judge1 objectAtIndex:6] career:[Judge1 objectAtIndex:7] judgecode:[Judge1 objectAtIndex:8]];
NSLog(@"%@",[JudgeTemp getName]);
[Judges addObject:JudgeTemp];
NSLog(@"%@",[[Judges objectAtIndex:i]getName]);
}
法官类
@implementation Judge
NSString *name;
NSString *picture;
NSString *courtroom;
NSString *phone;
NSString *undergrad;
NSString *lawschool;
NSString *opdasa;
NSString *career;
NSString *judgecommentcode;
-(void) setName:(NSString *)n picture:(NSString *) p courtroom:(NSString *)c phone:(NSString *)ph undergrad: (NSString *) u lawschool: (NSString *)l opdasa: (NSString *) o career: (NSString *)ca judgecode: (NSString *)jcode{
name = n;
picture = p;
courtroom = c;
phone = ph;
undergrad = u;
lawschool = l;
opdasa = o;
career = ca;
judgecommentcode = jcode;
}
-(NSString*) getName{
return name;
}
您正在创建具有相同数据的所有对象,那么如何知道它们是同一个对象?看起来你应该得到不同的对象,但是如果你已经做出判断一个单身或者用对象创建过程中的其他方法,那么你每次都可能得到同一个对象。 – Caleb 2014-08-31 15:41:10
他们并不都具有相同的数据(他/她在每次迭代时记录结果并表示他们没有),并且在这里似乎没有单身或类似的东西。 – Dima 2014-08-31 15:45:06
我在for循环之后通过Judges数组运行,每个对象都是for循环中创建的最后一个对象。其他答案似乎指向添加[JudgeTemp发布],但我不能在ARC中这样做。我还应该提到“Judge1”变量名称很差,但是它是一个NSStrings数组。 – user3157910 2014-08-31 15:45:31