简体   繁体   English

是否会部分使用对象导致内存泄漏?

[英]Does partially used object cause memory leak?

I have prepared a class for storing data retrieved from db, and let's say I have 10 vars in it. 我准备了一个用于存储从db检索到的数据的类,假设我有10个var。 What if I will reuse this class for different views and each view will use a different quantity of variables. 如果我将此类用于不同的视图,并且每个视图将使用不同数量的变量,该怎么办?

tableViewCell will pop-up 3 vars. tableViewCell将弹出3个变量。 View1 will pop-up 6 vars. View1将弹出6个变量。 View2 will pop-up 10 vars. View2将弹出10个变量。

Will the unused data cause memory leaks? 未使用的数据会导致内存泄漏吗?

A memory leak only happens when you delete all pointers to the memory before freeing it. 仅当在释放内存之前删除所有指向该内存的指针时,才会发生内存泄漏。 If you reuse your data structure, you might have some unused memory, but it won't be a leak unless you never free it when the pointers go away (leaving you no way to free it ever again). 如果重用数据结构,则可能会有一些未使用的内存,但是除非指针消失后再也不释放它,否则它不会泄漏(从而使您无法再次释放它)。

Unused variables have nothing to do with memory leaks. 未使用的变量与内存泄漏无关。 You want to see a memory leak? 您想看到内存泄漏吗?

- (void)leakABunchOfMemory {
    for (int i = 0; i < 1000000000; i++) {
        NSMutableString *usedButNotUsedCorrectly = [[NSMutableString alloc] initWithFormat:@"%d", i];
    }
}

That's a memory leak. 那是内存泄漏。 An object is created with every [NSMutableString alloc] , and none can never be destroyed because you lose your reference to them as soon as that iteration of the loop ends. 每个[NSMutableString alloc]都会创建一个对象,并且永远不会销毁任何对象,因为一旦循环迭代结束,您就失去对它们的引用。 They just go on existing and taking up space, like text-based zombies that hunger for the RAM of the living. 它们只是继续存在并占用空间,就像渴望活生生的RAM的基于文本的僵尸一样。 To avoid leaks in Objective-C code, follow the memory management rules , and the equivalent rules for any other libraries you use. 为避免在Objective-C代码中泄漏,请遵循内存管理规则以及您使用的任何其他库的等效规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM