我主要使用Java编程,无法理解为什么这不起作用。我正试图在我的for循环中创建一个临时对象“Judge”。然后我想将该对象添加到NSMutableArray中,所以最后我有一个填充了不同Judge对象的数组。在for循环之后,我遍历了Array中的所有对象,它们都是最后一个Judge对象。
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;
}
答案 0 :(得分:3)
问题在于您的Judge
课程。直接在@implementation
中定义变量时,它们具有全局范围而不是实例变量。您需要做的是将这些变量声明放在@interface
中:
@interface Judge : NSObject {
NSString *name;
NSString *picture;
NSString *courtroom;
NSString *phone;
NSString *undergrad;
NSString *lawschool;
NSString *opdasa;
NSString *career;
NSString *judgecommentcode;
}
// ...
@end
修改:显然您可以在@implementation
中声明它们,您只需将它们包装在{ }
中即可。请参阅:Instance variables declared in ObjC implementation file