Error: Variable-sized object may not be initialized. But why?

安稳与你 提交于 2019-12-25 01:53:19

问题


enter code hereint quantity = [array count];
int i;
for (i=0; i<quantity; i++) 
{
    NSString *imageName = [NSString stringWithFormat:@"Car_%@.jpg",  [[array objectAtIndex:i] objectForKey:@"CarName"]]   ];
    UIImage *img[i] = [UIImage imageNamed:imageName];
    UIImageView *imgView[i] = [[UIImageView alloc] initWithImage:img[i]];
    imgView[i].frame = CGRectMake(i*kWidth, 0, kWidth, kHeight);
    [scrollView addSubview:imgView[i]];
    [imgView[i] release];
}`enter code here`

Error: Variable-sized object may not be initialized. But why?


回答1:


You may want to try this:

int i;
for (i=0; i<quantity; i++) 
{
    NSString *imageName = [NSString stringWithFormat:@"Car_%@.jpg",  [[array objectAtIndex:i] objectForKey:@"CarName"]]   ];
    UIImage *img = [UIImage imageNamed:imageName];
    UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
    imgView.frame = CGRectMake(i*kWidth, 0, kWidth, kHeight);
    [scrollView addSubview:imgView];
    [imgView release];
}

You don't need to use img[i] in order to populate a scrollview with UIImageView.




回答2:


UIImage *img[i] = [UIImage imageNamed:imageName];

This declares a C-style array of size i and attempts to initialise it with an instance of UIImage. That doesn't make sense. What are you trying to do? Where is the rest of your code?

Edit:

Okay, I think I see what you are doing. Just get rid of all the places you have [i]. Inside the loop, you are only dealing with one item at a time, and even if you weren't, that's not how you use arrays.



来源:https://stackoverflow.com/questions/6550653/error-variable-sized-object-may-not-be-initialized-but-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!