目标c动态值分配

时间:2012-11-01 08:57:21

标签: iphone objective-c ios xcode

NSString *one = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"id",@"Test1",@"text", nil];
    NSString *two = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"id",@"Test2",@"text", nil];
    NSString *three = [NSDictionary dictionaryWithObjectsAndKeys:@"3",@"id",@"Test3",@"text", nil];

    _options = [NSArray arrayWithObjects:one,two,three,nil];

这是我在代码中使用并正常运行的代码。现在我想要动态,比如

int total = 20;
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for(int x = 0; x < total; x++)
    {
        [arr addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"id",@"Test1",@"text", nil]];
    }

但它不起作用。任何人都可以帮助我解决这个问题。

主要代码就像

_options = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"id",@"Test1",@"text", nil],[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"id",@"Test1",@"text", nil],[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"id",@"Test1",@"text", nil],nil];

我想动态创建它,比如值为1-100。我怎么能这样做

2 个答案:

答案 0 :(得分:2)

你可能遇到了一个试图将原语放入NSDictionary的问题,这是不可能的。将您的值转换为字符串。

for(int x = 1; x <= 100; x++) {
    NSString* object1 = [NSString stringWithFormat:@"%d", x];
    NSString* object3 = [NSString stringWithFormat:@"Test%d", x];
    [arr addObject:[NSDictionary dictionaryWithObjectsAndKeys:object1,@"id",object3,@"text", nil]];
}
[_options addObjectsFromArray:arr];

答案 1 :(得分:1)

你应该:

int total = 20;
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for(int x = 0; x < total; x++)
    {
          NSString *idStr = [NSString stringWithFormat:@"%d", x+1];
          [arr addObject:[NSDictionary dictionaryWithObjectsAndKeys: idStr,@"id",@"Test1",@"text", nil]];
    }