【问题标题】:Increasing number part of UIImageView variable in a for loop?在 for 循环中增加 UIImageView 变量的数量部分?
【发布时间】:2010-09-10 13:06:45
【问题描述】:

我有一个名为 myPicture1、myPicture2 和 myPicture3 的三个 UIImageView 变量。在 for 循环中,我试图将 myPicture 末尾的数字增加 1,以便我可以为三个变量中的每一个分配一个随机图像。下面是代码:

for (i=0; i<3; i++) {

int g = arc4random() % 19;

NSString *imagename = [NSString stringWithFormat:@"image%d.jpg",g];

UIImage *picture = [UIImage imageNamed:imagename];

 UIImageView imageView = [[UIImageView alloc] initWithImage : picture];

 self.myPicture1 = imageView; **This is where I want myPicture to increase to myPicture 2 and then 3 **

}

这可能吗?

谢谢大家,

马丁

【问题讨论】:

  • 如果你有 retaincopy 属性,你并不是在泄漏 imageView。你应该在调用属性设置器后release它。

标签: objective-c c xcode loops for-loop


【解决方案1】:

好吧,我认为你在处理这个问题时有点尴尬。
可能最好的方法是将您的UIImageViews 存储在NSArray 中。 所以在你的类声明中,而不是

@property (nonatomic, retain) UIImageView *myPicture1;
@property (nonatomic, retain) UIImageView *myPicture2;
@property (nonatomic, retain) UIImageView *myPicture3;

你会的

@property (nonatomic, retain) NSArray *myPictures;

然后你像这样创建它们:

NSMutableArray *myTempArray = [NSMutableArray arrayWithCapacity:3];
for (i=0; i<3; i++)
{
    int g = arc4random() % 19;

    NSString *imagename = [NSString stringWithFormat:@"image%d.jpg",g];
    UIImage *picture = [UIImage imageNamed:imagename];

    UIImageView imageView = [[UIImageView alloc] initWithImage : picture];
    [myTempArray addObject: imageView];
    [imageView release];
}
self.myPictures = [NSArray arrayWithArray: myTempArray];

【讨论】:

  • 最好使用copy 作为属性,因为NSArray 在可变/不可变类集群中。然后你可以简单地说self.myPictures = myTempArray;。还有imageView被泄露了,添加到数组后必须释放。
猜你喜欢
  • 2013-11-25
  • 2017-03-22
  • 1970-01-01
  • 2017-01-26
  • 2018-12-25
  • 2016-04-14
  • 1970-01-01
  • 2011-02-24
  • 1970-01-01
相关资源
最近更新 更多