-2

我有这个...

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]"];
}

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

4

3 回答 3

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

应该

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

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

此外,还有一种更短的方法可以intNSString

[NSString stringWithFormat:@"%d", i];

可以替换为

@(i).stringValue

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

于 2013-04-12T21:17:54.437 回答
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];
}
于 2013-04-12T21:21:17.783 回答
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]];

}];
于 2013-04-12T21:27:57.910 回答