Obj-C:在循环中正确释放分配的对象
希望我能很好地解释这一点。 假设如下:
@interface ClassA : NSObject {
NSMutableArray firstArray;
NSArray secondArray;
}
#import "ClassA"
@interface ClassB : NSObject {
ClassA classAobject;
}
然后在程序“伪代码”的其他部分访问字典键,例如:
NSMutableArray* sample = [[NSMutableArray alloc] init];
for (keys in Data)
{
ClassA* aObj = [[ClassA alloc] initWith: objectForKey:@"KeyHere" andWith:@"Key2Here"];
ClassB* bObj = [[ClassB alloc] init];
[bObj setClassAObj: aObj];
[sample addObject: bObj];
}
Singleton* single = [Singleton single];
[single setArray: sample];
我的问题是在循环内部创建的 ClassA 和 ClassB 对象以及在循环外部存储它们的数组。我是否因不释放它们而泄漏内存?如果我确实释放它们,我怎样才能以一种不会丢失存储“样本”数组的单例中对它们的引用的方式来释放它们?
如果重要的话,存储它的 Singleton 数组会在类的“init”方法中分配和初始化。
Hopefully I can explain this well.
Assume the following:
@interface ClassA : NSObject {
NSMutableArray firstArray;
NSArray secondArray;
}
#import "ClassA"
@interface ClassB : NSObject {
ClassA classAobject;
}
Then in some other part of the program 'Psuedo-code' accessing dictionary keys like:
NSMutableArray* sample = [[NSMutableArray alloc] init];
for (keys in Data)
{
ClassA* aObj = [[ClassA alloc] initWith: objectForKey:@"KeyHere" andWith:@"Key2Here"];
ClassB* bObj = [[ClassB alloc] init];
[bObj setClassAObj: aObj];
[sample addObject: bObj];
}
Singleton* single = [Singleton single];
[single setArray: sample];
My question is with the ClassA and ClassB objects created inside the loop and the array to store them outside of the loop. Am I leaking memory here, by not releasing them? If I do release them, how can I do so in a way that I wont lose the reference to them in the singleton to which I am storing the 'sample' array?
If it matters, the Singleton array to which it is being stored is allocated and initialized in the "init" method of the class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将对象添加到数组中会保留对象。因此,您需要在添加它们后释放它们(如果不是自动释放)。同样,您需要确保实例变量数组(在单例中)的@properties设置为retain,以便在单例中设置时保留示例数组。然后您还需要发布示例。
此外,您的实例变量需要是指针:
Adding objects to an array retains the objects. So you need to release them after you add them (if not autoreleased). Similarly, you need to make sure that the @properties for the instance variable array (in Singleton) is set to retain so that the sample array is retained when set in the singleton. Then you need to release sample as well.
Also, your instance variables need to be pointers:
NSMutableArray 在对象被添加和删除时分别执行保留和释放。因此,您会为分配获得一个保留,然后为添加获得第二个保留。当数组被破坏时,它会释放一个。这使得保留计数为 1。
您可以进行这些自动释放。我相信将内存一起释放可以提高性能,并且是推荐的方法。
NSMutableArray performs retain and release on objects as they are added and removed respectively. So you get one retain for the alloc, and then a second retain for the add. When the array is destroyed, it will release one. That leaves you with a retain count of 1.
You can make these autorelease. I believe it improves performance to have the memory released together and is the recommended approach.