2

这个:

    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,那是行不通的。所以它似乎也有点摇摆不定。

4

2 回答 2

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];
}
于 2009-09-30T12:08:50.427 回答
0

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

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

Sign = nil
[Sign release]

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

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

于 2009-09-30T12:09:20.713 回答