does removefromsuperview releases the objects of s

2020-02-23 08:37发布

问题:

  for(UIView *subview in [scrollView subviews]) {
    NSLog(@"subviews Count=%d",[[scrollView subviews]count]);
    //[subview release];
    [subview removeFromSuperview];
}

in the above method if i use [subview removeFromSuperview]; it works fine...but if i use [subview release];It crashes..i want to know that if both are same or is there any difference between them?

回答1:

@MathieuK is correct, but it's worth digging deeper into this, because it's a very important concept in ObjC. You should never call -release on an object you didn't -retain explicitly or implicitly (by calling one of the Three Magic Words). You don't call -release in order to deallocate an object. You call it to release the hold you have put on the object. Whether scrollview is retaining its subviews is not your business (it does retain its subviews, but its still not your business). Whether -removeFromSuperview calls -release is also not your business. That's betweeen the scrollview and its subviews. All that matters is that you retain objects when you care about them and release them when you stop caring about them, and let the rest of the system take care of retaining and releasing what it cares about.



回答2:

The retain count of your subviews is probably 1. When you call [subview release]; the retain count becomes 0 and the subview is released from memory. The subsequent access to subview (to call removeFromSuperview) crashes because subview isn't there anymore.

In this case you should just call [subview removeFromSuperview] because removeFromSuperview will call release on subview itself.



回答3:

You need to revise the Cocoa Memory Management.

You simply do not release things that you have not explicitly allocated or retained yourself.



回答4:

No they are not the same , if you checked the

retainCount

after

removeFromSuperView

you will see that nothing is changed , so you can add the same view again without allocating it!!

plus you should never release an object that you have never allocated!!