简体   繁体   中英

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. 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. View1 will pop-up 6 vars. View2 will pop-up 10 vars.

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. They just go on existing and taking up space, like text-based zombies that hunger for the RAM of the living. To avoid leaks in Objective-C code, follow the memory management rules , and the equivalent rules for any other libraries you use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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