开发者

release vs setting-to-nil to free memory

开发者 https://www.devze.com 2023-01-02 05:24 出处:网络
In my root view controller, in my didReceiveMemoryWarning method, I go through a couple data structures (which I keep in a global singleton called DataManager), and ditch the heaviest things I\'ve got

In my root view controller, in my didReceiveMemoryWarning method, I go through a couple data structures (which I keep in a global singleton called DataManager), and ditch the heaviest things I've got--one or maybe two images associated with possibly twenty or thirty or more data records.

Right now I'm going through and setting those to nil. I'm also setting myself a boolean flag so that various view controllers that need this data can easily know to reload. Thusly:

DataManager *data = [DataManager sharedDataManager];
for (Event *event 开发者_StackOverflowin data.eventList) {
    event.image = nil;
    event.thumbnail = nil;
}

for (WondrMark *mark in data.wondrMarks) {
    mark.image = nil;
}

[DataManager sharedDataManager].cleanedMemory = YES;

Today I'm thinking, though... and I'm not actually sure all that allocated memory is really being freed when I do that. Should I instead release those images and maybe hit them with a new alloc and init when I need them again later?


Setting an instance variable directly, as mipadi says, does not release the object it refers to. What you're doing here is different, though: you're setting the value of object's property. Depending on how that property is declared, that may indeed be releasing the value it refers to. A property declared retain or copy, rather than assign, gets a synthesized accessor method (the setImage: method that the .image = syntax translates to) that releases its old value when setting a new one. So, in this case, if your WondrMark's property is declared as retain, setting it to nil—via the property—does automatically release the old image. If it's assign, you need to release the image before setting the property to nil.


Objects are not freed when you set them to nil, so yes, you should release them.


You should not be directly releasing other objects' instance variables or properties. Those objects are responsible for doing so themselves.

However, if can object releases its instance variables when a new one is set (such as with retain properties), then setting the instance variable to nil will have cause the object to release the old value.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号