NSMutableArray添加到一个循环中

时间:2013-04-12 21:14:14

标签: ios xcode arrays nsmutablearray cycle

我有这个......

allTableData = [[NSMutableArray alloc] initWithObjects:
 [[Food alloc] initWithName:@"1" andDescription:@"Hi man!"],
 [[Food alloc] initWithName:@"2" andDescription:@"Hi woman"],
nil ];

我该怎么办?

NSArray *array = [NSArray arrayWithObjects:@"Hi man",@"Hi woman",nil]; 
allTableData = [[NSMutableArray alloc] initWithObjects
for(i=0; i<2; i++)
{
   NSString *aString = [NSString stringWithFormat:@"%d", i];
   [[Food alloc] initWithName:aString andDescription:@"array[i]"];
}

......以及通过一个循环进入?

3 个答案:

答案 0 :(得分:1)

[[Food alloc] initWithName:aString andDescription:@"array[i]"];

应该是

[[Food alloc] initWithName:aString andDescription:array[i]];

在第一种情况下,您添加了字符串"array[i]",而您想要访问数组的第i个元素。

此外,将int转换为NSString

的方法较短
[NSString stringWithFormat:@"%d", i];

可以替换为

@(i).stringValue

数字的@语法是llvm 3.3引入的一项功能,允许您创建NSNumbers文字。 NSNumber然后使用方法stringValue来获取所需的NSString

答案 1 :(得分:0)

试试这个

NSArray *array = [NSArray arrayWithObjects:@"Hi man",@"Hi woman",nil]; 
allTableData = [NSMutableArray array];
for(i=0; i<[array count]; i++){
   NSString *aString = [@(i) stringValue];
   Food *food = [[Food alloc] initWithName:aString andDescription:array[i]];
   [allTableData addObject:food];
}

答案 2 :(得分:0)

NSArray *array = [NSArray arrayWithObjects:@"Hi man",@"Hi woman",nil];
NSMutableArray* tableData = [NSMutableArray arrayWithCapacity:array.count];

[array enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL* stop){

[tableData addObject:[[Food alloc] initWithName:[@(index) stringValue] andDescription:obj]];

}];