在长时间休息后重新开始编码,然后选择目标C.
我想将多个对象添加到数组中。我可以明确地做到(如下所示),但我确信必须采用更智能,迭代的方式来实现它。
NSMutableArray *a =[NSMutableArray array];
Class A *c1 = [[Class A alloc]init];
[c1 setVAlueX:5];
[c1 setValueY:3];
[a addobject:c1];
Class A *c2 = [[Class A alloc]init];
[c2 setVAlueX:5];
[c2 setValueY:3];
[a addobject:c2];
Class A *c3 = [[Class A alloc]init];
[c3 setVAlueX:5];
[c3 setValueY:3];
[a addobject:c3];
等
答案 0 :(得分:3)
这很好而且简短:
NSArray *a = @[[A aWithX:5 Y:3], [A aWithX:5 Y:3], [A aWithX:5 Y:3]];
你必须在A类中实现一个便利构造函数:
+ (instancetype)aWithX:(int)x Y:(int)y
{
A *a = [[self alloc] init];
[a setValueX:x];
[a setValueY:y];
}
答案 1 :(得分:-3)
试试这个
NSMutableArray *a =[[NSMutableArray alloc] init];
NSMutableArray *b =[[NSMutableArray alloc] init];
NSMutableArray *c =[[NSMutableArray alloc] init];
NSMutableDictionary *dictA = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dictB = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dictC = [[NSMutableDictionary alloc] init];
Class A *c1 = [[Class A alloc]init];
[dictA setObject:[NSString stringWithFormat:@"5"] forKey:@"ID1"];
[dictA setObject:[NSString stringWithFormat:@"3"] forKey:@"ID1"];
//[c1 setVAlueX:5];
//[c1 setValueY:3];
[a addobject: dictA];
Class A *c2 = [[Class A alloc]init];
[dictB setObject:[NSString stringWithFormat:@"5"] forKey:@"ID1"];
[dictB setObject:[NSString stringWithFormat:@"3"] forKey:@"ID1"];
//[c2 setVAlueX:5];
//[c2 setValueY:3];
[a addobject: dictB];
Class A *c3 = [[Class A alloc]init];
[dictC setObject:[NSString stringWithFormat:@"5"] forKey:@"ID1"];
[dictC setObject:[NSString stringWithFormat:@"3"] forKey:@"ID1"];
//[c3 setVAlueX:5];
//[c3 setValueY:3];
[a addobject: dictC];