0

我正在使用 for 语句来枚举数组中的所有对象。对于数组中的每个对象,我想创建它,以便它每次创建一个不同的对象,以便我可以引用不同的对象,例如数组中有 5 个字符串对象。我使用 for 语句枚举每个对象,并且每次我想创建一个包含文本 @"hello" 的 nsmutablestring

for (NSString *string in array) {

 // Ignore string variable
 NSMutableString *
 // I have this problem, how do I code it so that it makes a new                                               NSMutableString with a separate name that i can specify 
 // so i can refer to it
  = [NSMutableString alloc] init];

   // More code that is not relevant

}

万一你不明白这里是不是简单......在一个数组中 - 5个对象枚举数组并每次使用单独的名称创建一个新对象,以便我可以引用它:object1 object2 object3 object4 object5

更新:

数组我的意思是 NSArray

我的问题是我正在添加 uiimageview ...

4

3 回答 3

2

我不确定你的问题......数组对象已经由它们的索引唯一标识。为什么需要不同的名称(NSString * 指针)???

当您已经知道该数组中有多少个字符串以及每个字符串代表什么时,这可能是相关的。(例如,表示程序的一些配置参数的字符串数组......如果有人想到更好的例子:)在这种情况下,如果您想有一种清晰而独特的方式来访问数组的每个成员,您不需要不同的指针名称,只需使用 int 常量作为数组的索引 - (例如在 C 宏中或在枚举中声明)

于 2011-11-26T14:55:28.980 回答
1

不要使用 a for (... in ...),仅使用以下标准:

NSArray *oldArray;
NSMutableArray *newArray;

for (int i = 0; i < oldArray.count; i++)
{
    UIImageView *view = [UIImageView new];
    view.tag = i;
    [newArray addObject:view];
    [view release];
}

NSLog(@"%@", newArray);

编辑:更新下面的评论

于 2011-11-26T14:37:14.630 回答
1

如果我正确理解您的问题,我会使用另一个数组

NSMutableArray * arrayOfNewObjects = [[NSMutableArray alloc] init];
for (int n = 0; n < [array count]; n++) {
    //[array objectAtIndex:n] is original object
    [arrayOfNewObjects addObject:[NSMutableString stringWithString:@"hello"]];
}
//[arrayOfNewObjects objectAtIndex:0] would be your first object
于 2011-11-26T14:41:33.323 回答