-(id) initWithData:(NSString *)lastName: (NSString *)firstName{
self->firstname = firstName;
self->lastname = lastName;
return self;
}
-(void) printData {
NSLog(@"firstname: %@", firstname);
NSLog(@"lastname: %@", lastname);
}
所以每当我使用上面的init函数创建一个新对象时。并使用addObject函数将对象添加到NSMutableArray。
NSMutableArray *objectArray = [[NSMutableArray alloc] init];
CustomObject *tempObject = [[CustomObject alloc] initWithData: @"smith": @"john"];
CustomObject *tempObjectb = [[CustomObject alloc] initWithData: @"brown": @"william"];
[objectArray addObject:tempObject];
[objectArray addObject:tempObjectb];
[[objectArray objectAtIndex:0] printData];
[[objectArray objectAtIndex:1] printData];
索引为1的对象,0总是等于最后添加到数组中的对象 如果我使用for循环,或者有两个以上的对象,打印时的所有值,转到objectArray的最后添加对象的值,也会发生这种情况。如果有任何我遗漏的信息,请告诉我。 有什么东西我错过了吗?
答案 0 :(得分:0)
修复您的initWithData:lastName:
实施,如下所示:
-(id) initWithData:(NSString *)lastName: (NSString *)firstName
{
self = [super init];
if ( nil != self ) {
self->firstname = [firstName retain];
self->lastname = [lastName retain];
}
return self;
}