【问题标题】:An array of UIImageViews in objective-cObjective-c 中的 UIImageViews 数组
【发布时间】:2013-07-20 22:13:16
【问题描述】:

我已经有很多 UIImageViews 了。我想创建一个 UIImageViews 数组,并将数组的每个元素分配给上面的 UIImageViews 之一。我如何使用目标 c 来做到这一点? 我在java中做了如下:

JLabel l1=new JLabel();
JLabel l2=new JLabel();
JLabel [] arrayOfLabels = new JLabel[2];
arrayOfLabel[0] = l1;
arrayOfLabel[1] = l2;

我需要在目标 c.. 中做同样的事情。

【问题讨论】:

  • 您在哪里有很多图像浏览量?它们是如何定义的?

标签: java objective-c arrays uiimageview


【解决方案1】:

为了更清楚,让我根据您的 Java 语句回答您:

   //Java:
    JLabel l1=new JLabel();

    //Objective C:
    UIImageView * l1= [[UIImageView alloc] init];


    //Java:
    JLabel l2=new JLabel();

    //Objective C:
    UIImageView * l2 = [[UIImageView alloc] init];


    //Java 
    JLabel [] arrayOfLabels = new JLabel[2]; 

    //Objective C 
    NSMutableArray * imagesArray = [[NSMutableArray alloc] init];

    //Java 
    arrayOfLabel[0] = l1;

    //Objective C 
    [imagesArray addObject:l1];


    //Java
    arrayOfLabel[1] = l2; 

    //Objective C
    [imagesArray addObject:l2];

由于您没有使用 ARC(我从您的评论中猜到了),因此您必须手动释放这些东西作为内存管理的一部分:

     [l1 release];  //After adding it to imagesArray

     [l2 release];  //After adding it to imagesArray

并在不需要时释放imagesArray。通常它是在dealloc() 中完成的,但是您可以在不需要它的任何时候释放它,只需调用:

    [imagesArray release];
    imagesArray = nil;

希望这会对你有所帮助。

【讨论】:

  • imagesArray[0] = l1 也是合法的,更像是 java-esque。
  • 只要使用 ARC @nouf,当然除非有一个很好的理由你不能......在那种情况下 [imagesArray release] 当你不再需要它时。和 [l1 release][l2 release] 将它们添加到数组之后。
【解决方案2】:
UILabel * l1 = [[UILabel alloc] init];
UILabel * l2 = [[UILabel alloc] init];
NSMutableArray * arrayOfLabels = [NSMutableArray arrayWithCapacity:2];
arrayOfLabels[0] = l1;
arrayOfLabels[1] = l2;

【讨论】:

    【解决方案3】:
    UIImageView *view1;
    UIImageView *view2;
    // assuming they are already instantiated
    NSMutableArray *arrayOfImageViews = [[NSMutableArray alloc] init];
    [arrayOfImageViews addObject:view1];
    [arrayOfImageViews addObject:view2];
    

    【讨论】:

    • 所以 view1 在索引 0 和 view2 在索引 1 对吗??.. 如果我想将索引 1 处的元素更改为 view1 怎么办?我的意思是如何访问特定元素进行修改??
    • 那就是[arrayOfImageViews replaceObjectAtIndex:1 with Object:view1];。请注意,该数组包含指向真实对象(例如 view1、view2)的 指针。您不能修改指针,只能替换。但是,您可以修改指针指向的元素。您可以通过[arrayOfImageViews objectAtIndex:1]访问它
    【解决方案4】:

    使用您可以说的更现代的语法

    NSArray *myViewArray=@[ view1, view2, view3 ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 2011-02-17
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多