Is calling [self release] allowed to control object lifetime?

前端 未结 6 2275
终归单人心
终归单人心 2020-12-07 00:40

I want to create an object in Objective C but I don\'t hold a reference to it.

Is it allowed to let the object control its own lifetime by calling [self release]?

6条回答
  •  不知归路
    2020-12-07 01:04

    If you see this in code, its probably wrong. However there are legitimate response for it in certain circumstances that are arguably defensible. (So make sure you are doing it for the right reasons.)

    A good example of when this makes sense, is when you create an object that goes off to download a url. The object sits in memory while downloading the url, then sends a message to its delegate saying the data is ready (or url couldn't be downloaded). Once its message has been sent it destroys itself as its no longer needed. In this situation the code/function that created the 'url downloader' may no longer even be in memory, i.e. if it was called in response to a user selection a menu item or an action in a view controller that is no longer on the screen.

    This is useful when the code that creates the "download" object doesn't care if the download completes or not.

提交回复
热议问题