管理阵列的正确方法

时间:2014-12-02 02:33:52

标签: ios objective-c arrays

我正在使用可变数组。我不确定这是管理阵列的正确方法。我试图学习内存管理基础知识,但我发现它太难掌握了。我正在做的是

在接口处声明数组

@interface myVC()
@property (nonatomic,strong) NSMutableArray *substrings; // if I use weak attribute here,does it change anything?
 @end


 -(void)myMethod{

  // initializing the array
   _substrings=[[NSMutableArray alloc]init];

   //storing some data into it
    [_substrings addObject:@"hello"];

    //do something with the data in that array
       //call another method which gets the data from this same array and do some operations there
            [self method2];-----> // I access data from the array like, x=[_substrings objectatindex:0];

     //finally, remove the items in the array
      [_substrings removeObject:@"hello"];

       //and again start the process as mentioned here


    }

这就是我的想法。这是一种声明和访问和管理数组的正确方法吗?

1 个答案:

答案 0 :(得分:1)

一般来说它会起作用,但是我建议使用属性getter / setter访问这个数组。这样,如果您需要创建自定义getter / setter,则无需重构所有代码。

@interface myVC()
@property (nonatomic, strong) NSMutableArray *substrings; 
@end


-(void)myMethod{

  // initializing the array
  _substrings=[[NSMutableArray alloc]init];

  //storing some data into it
  [self.substrings addObject:@"hello"];

  [self method2];-----> // I access data from the array like, x=[self.substrings objectatindex:0];

  //finally, remove the items in the array
  [self.substrings removeObject:@"hello"];
}