NSMutableArray 多维,removeAllObjects?
NSMutableArray multidimensional, removeAllObjects?
ObjC w/ARC
在我将 NSMutableArray
的新实例重新分配给它之前,我是否需要在先前初始化的 NSMutableArray
(设置为多维,顺便说一句)上调用 removeAllObjects
?
考虑:
@interface MyClass
@property(strong) NSMutableArray *myArray;
@end
@implementation MyClass
-(instancetype)init {
if (self = [super init]) {
[self initializeMyArrayWithData] // once
[self initializeMyArrayWithData] // twice
}
return self;
}
-(void)initializeMyArrayWithData {
NSMutableArray *temp = [NSMutableArray arrayWithCapacity:8];
for (int row = 0; row < 8; row++) {
[temp addObject: [NSMutableArray arrayWithCapacity:8]];
for (int col = 0; col < 8; col++) {
[[temp objectAtIndex:row] insertObject:@"TEST" atIndex:col];
}
}
// let's assume my array was previously initialized
// with this method. Do I need to "clean-up" the previous
// instance by removing all objects within it, or will
// this be handled automatically by the property method using
// the following simple assignment?
self.MyArray = temp;
}
@end
不,您不必这样做。下面是发生的事情:ARC 将告诉 self.MyArray
中引用的 NSMutableArray
的当前实例它已被释放。假设它是唯一的引用,数组将开始释放它的内容,释放它的每个对象。
ObjC w/ARC
在我将 NSMutableArray
的新实例重新分配给它之前,我是否需要在先前初始化的 NSMutableArray
(设置为多维,顺便说一句)上调用 removeAllObjects
?
考虑:
@interface MyClass
@property(strong) NSMutableArray *myArray;
@end
@implementation MyClass
-(instancetype)init {
if (self = [super init]) {
[self initializeMyArrayWithData] // once
[self initializeMyArrayWithData] // twice
}
return self;
}
-(void)initializeMyArrayWithData {
NSMutableArray *temp = [NSMutableArray arrayWithCapacity:8];
for (int row = 0; row < 8; row++) {
[temp addObject: [NSMutableArray arrayWithCapacity:8]];
for (int col = 0; col < 8; col++) {
[[temp objectAtIndex:row] insertObject:@"TEST" atIndex:col];
}
}
// let's assume my array was previously initialized
// with this method. Do I need to "clean-up" the previous
// instance by removing all objects within it, or will
// this be handled automatically by the property method using
// the following simple assignment?
self.MyArray = temp;
}
@end
不,您不必这样做。下面是发生的事情:ARC 将告诉 self.MyArray
中引用的 NSMutableArray
的当前实例它已被释放。假设它是唯一的引用,数组将开始释放它的内容,释放它的每个对象。