如何重用UILabel? (或任何对象)

时间:2009-09-30 11:37:17

标签: iphone objective-c loops initialization definition

此:

    UILable *myLabel = [[UILabel alloc] init];
    UILable *myLabel = [[UILabel alloc] init];

给我一​​个重新定义错误。

但是这个:

    for(i=0;i<5;i++)
    { 
       UILable *myLabel = [[UILabel alloc] init];
       // some label code here
       [self.view addSubview:myLabel];
       [myLabel release];
    }

没有。第二个是假的吗?我应该在之前定义它并重新使用它吗?

是吗:

 UIIMageView *Sign;
//Some Sign Stuff
     Sign = [[UIImageView alloc]init];
        Sign.image = [UIImage imageNamed:@"Minus.png"]; 
        frame = CGRectMake(160 ,80, 64, 64);
        Sign.frame = frame;
        [scrollView addSubview:Sign];
        Sign = nil;
        [Sign release];
//Some other Sign stuff
     Sign = [[UIImageView alloc]init];
        Sign.image = [UIImage imageNamed:@"Plus.png"];  
        frame = CGRectMake(200 ,80, 64, 64);
        Sign.frame = frame;
        [scrollView addSubview:Sign];
        Sign = nil;
        [Sign release];

是正确的吗?没有Sign = nil,这不起作用。所以它看起来有点不稳定。

2 个答案:

答案 0 :(得分:1)

您不能在同一块级别范围内使用相同的变量名称。因此,在您的第一个示例中,您不能使用相同名称的变量定义,您必须以不同的方式命名它们。

- (void) method {
   UIImageView* image1;

   // here we define a new block scope. This can be a block of any kind (while, for, if)
   {
      // All reference in this block to this variable will see this definition.
      UIImageView* image1;

      // Using image1 here
   }

   // Here we see again the image1 defined at the beginning of the method.
}

在你的循环示例中,您处于一个新的范围内,它在每次迭代后重新初始化。

你的第三个例子是正确的,因为它只定义了一次变量。之后重复使用此变量来分配新对象。第三个不太优雅,因为你的变量名称并不能很好地描述每种情况的目的。

对于'Sign = nil'的情况,这有效地使得后面的行无用,因为在Objective-C中,发送到nil对象的消息被忽略。

我建议您定义一个方法,您可以调用该方法来创建看起来相同的图像。类似的东西:

- (void) createImage:(NSString*) image frame:(CGRect) frame {
  UIImageView *Sign;
  Sign = [[UIImageView alloc]init];
  Sign.image = [UIImage imageNamed:image]; 
  Sign.frame = frame;
  [self.scrollView addSubview:Sign];
  [Sign release];
}

答案 1 :(得分:0)

你的for循环非常好。 myLabel的范围仅限于你的for循环的一次运行。因此,每次运行一个新变量来保存对你的UILabel的引用。

您发布的第二个代码有泄漏。

Sign = nil
[Sign release]

这将释放地址为nil的对象,而不是您创建的对象。我看不出你的代码还有什么问题,但你的修复肯定没有解决根本原因。也许它有助于发布删除Sign = nil时得到的错误/警告。

另请注意,使用大写字母开始变量名称不是一个好的命名约定,因为通常类名称以1开头。