Objective-C addObject似乎将对象放入所有数组索引中
我正在努力学习如何制作简单的课程 到目前为止,使用addObject和我的类并没有得到预期的结果 以下是我所拥有的: 在我的视图控制器中:Objective-C addObject似乎将对象放入所有数组索引中,objective-c,Objective C,我正在努力学习如何制作简单的课程 到目前为止,使用addObject和我的类并没有得到预期的结果 以下是我所拥有的: 在我的视图控制器中: #import "onoffclass.h" 在其viewDidLoad中: NSMutableArray *inTable; onoffclass *therec; onoffclass *readrec; inTable = [NSMutableArray array]; therec = [[onoffclass alloc]in
#import "onoffclass.h"
在其viewDidLoad中:
NSMutableArray *inTable;
onoffclass *therec;
onoffclass *readrec;
inTable = [NSMutableArray array];
therec = [[onoffclass alloc]init];
readrec = [[onoffclass alloc]init];
for (int lop=0;lop<3;lop++){
therec.parsedID = [NSString stringWithFormat:@"%i",lop];
[inTable addObject:therec];
NSLog(@"lop=%i onoff.parsedID=%@",lop,therec.parsedID);
for (int z=0;z<[inTable count];z++){
readrec = inTable[z];
NSLog(@" inTable[%i] parsedID=%@",z,readrec.parsedID);
}
}
在我的onoffclass.m中:
#import <Foundation/Foundation.h>
#import "onoffclass.h"
@implementation onoffclass {
NSString *_parsedID;
NSString *_parsedOn;
NSString *_parsedOff;
NSString *_parsedAdj;
NSString *_parsedRoom;
NSString *_parsedBuilding;
NSString *_parsedWho;
NSString *_parsedInfo;
NSString *_parsedBillable;
}
-(onoffclass*)initWithSomeString: (NSString*)blah AndSomeNum: (int)num {
self = [super init];
_parsedID = blah;
_parsedOn = @"on";
_parsedOff = @"off";
_parsedAdj = @"adj";
_parsedRoom = @"room";
_parsedBuilding = @"building";
_parsedWho = @"who";
_parsedInfo = @"info";
_parsedBillable = @"billable";
return self;
}
-(NSString*)description {
return [NSString stringWithFormat: @"%@", _parsedID];
}
@end
为什么addObject似乎正在更新所有数组索引?我该如何解决这个问题
谢谢,
Dale您正在创建一个
onoffclass
的实例(顺便说一下,类名应该以大写字母开头),然后在循环中一次又一次地添加相同的实例。由于类是引用类型,因此更改属性会影响同一实例的所有引用
解决方案是将创建实例的行放入循环中
for (int lop = 0; lop < 3; lop++) {
therec = [[onoffclass alloc] init];
...
for(int-lop=0;lop<3;lop++){
therec=[[onoffclass alloc]init];
...
您正在创建一个onoffclass
的实例(按照类名以大写字母开头的方式),然后在循环中一次又一次地添加同一实例。由于类是引用类型,更改属性会影响同一实例的所有引用
解决方案是将创建实例的行放入循环中
for (int lop = 0; lop < 3; lop++) {
therec = [[onoffclass alloc] init];
...
for(int-lop=0;lop<3;lop++){
therec=[[onoffclass alloc]init];
...
当你不遵循命名约定时,阅读你的代码真的很困难……而且在空格字符方面要节俭;-)对不起,可以解决这个问题。当你不遵循命名约定时,阅读你的代码真的很困难……在空格字符方面要节俭;-)对不起,可以解决这个问题。
for (int lop = 0; lop < 3; lop++) {
therec = [[onoffclass alloc] init];
...