【问题标题】:Create an unknown number of objects创建未知数量的对象
【发布时间】:2011-08-12 18:01:30
【问题描述】:

我需要根据变量创建特定数量的对象实例。所以伪代码看起来有点像这样

for(int x; x < aInt; x++) {
    //create object and initialize it
}

我将如何做到这一点并每次创建一个具有不同名称和内存位置的不同对象?

【问题讨论】:

    标签: iphone objective-c object for-loop


    【解决方案1】:

    将参考贴在NSMutableArray(或NSArray,因为您似乎事先知道大小)。

    NSMutableArray *array = [[NSMutableArray alloc]init]
    
    for(int x; x < aInt; x++) {
        //create object and initialize it
        YourObject *o = [[YourObject alloc]init];
        [array addObject:o];
        [o release];
    }
    
    // do whatever you need to do with the objects
    

    NSDictionary/NSMutableDictionary 当然也是一种选择,具体取决于您的要求。

    【讨论】:

      【解决方案2】:

      只需使用NSMutableArray

      NSMutableArray *objectsArray = [NSMutableArray arrayWithCapacity:(YourIntegerValue)];
      for(int x; x < aInt; x++) {
          //create object and initialize it
          [objectsArray addObject:(YourObject)];
      }
      

      使用完数组后不要忘记释放

      【讨论】:

        猜你喜欢
        • 2012-01-07
        • 2016-04-13
        • 2014-11-27
        • 1970-01-01
        • 2012-08-21
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多