using [super ___]; ?

Discussion in 'iOS Programming' started by fenrus110, Oct 20, 2008.

  1. fenrus110 macrumors regular

    Mar 24, 2008
    One thing I noticed about the 2.1 SDK is that they began adding the [super___] to the templates, such as [super viewDidLoad];

    should we always be calling super for the inherited functions? Cuz the sample code doesn't always do it.

    Also, do you call 'super' at the end or the start of a function? I notice that [super dealloc]; always seems to go last, but for other functions, [super ___]; is the first line.
  2. SqueegyX macrumors regular

    Mar 24, 2008
    I think its a good best practice. I don't think the UIKit implementations of some of these methods do anything at all, but they might in a future update to the framework. If you left out the super, things would then break. If you leave it in, you're just calling a method that does nothing which is a tiny and trivial performance issue at worst.

    For viewDidLoad, it probably doesn't matter if it comes first or last. In dealloc it does because that is what actually remove objects from memory. So you need to make sure you clean an object out, before you delete it.
  3. hchung macrumors 6502a

    Oct 2, 2008
    Calling the super of the method you're overriding is so that the code that was there before gets called.

    To decide if you have to, consider the order of what needs to happen.

    For dealloc, do it at the end. This is because for every class your class inherits from, they need to clean up their instance variables. Typically you'll make the variables you create, then clean them up in the opposite order to avoid letting something go that you still need. If you make A, B, C, it's expected that C depends on B, which depends on A. This means you'll clean them up C, B, A.

    So when the object got created, it called super init so that all the other stuff you're inheriting gets created. Now when you're deallocating, you'll clean yourself up, and then call the super to continue the cleanup.

    In the case of viewDidLoad..... If you inherit from an object that prepares a bunch of stuff, you'll want to call super viewDidLoad first because otherwise it won't be prepared when you expect it to be.

    Here's another interesting one.
    On the desktop, NSViews have a "mouseDown" that happens when something's clicked.

    If you want to make sure that something's prepared when clicked, you'd want to do that first, and then call super mouseDown so that the mouseclick gets processed. If you called super mouseDown first, you'd end up doing the click and then preparing.... which sounds backwards, because it is.

Share This Page