简体   繁体   中英

Methods required to be implemented when subclassing in Objective C

I am new at programming in general (though I have had a C class many, many years ago) and am learning Objective-C for programming on the iPhone. I have what I think is a simple question, but after looking for a while (days, off and on) I can't find the answer that I'm looking for explicitly.

I know that when subclassing an Objective-C class I should implement the initialize method along with the deallocate method (unless using ARC for the latter, if I am correct?). The questions are:

  1. Are these the only two to worry about, or will other classes potentially have additional methods that can be required to be implemented?
  2. If other classes might have methods that I am required to implement when subclassing them, where is that documentation typically found? (I don't seem to see that in the Apple framework docs, though that kind of information is there for protocols it appears)

Thanks for your help!

  • Technically, you are not required to implement even the init and dealloc if the inherited versions are sufficient. Also, ARC does not free you from having to write dealloc in all cases (but it certainly covers the overwhelming majority). For example, if you allocate memory for your object using malloc , you need to free it in the dealloc .
  • When you add instance variables to your class, you need to initialize them. Typically, you do that in a designated initializer . Again, if you do not to initialize anything, you do not have to code your own initializer; same goes for deinitializer.
  • The only case when you need to implement a method is when you adopt a protocol with one or more methods marked @requried . These methods are marked in the protocol reference. For example, tableView:cellForRowAtIndexPath: and tableView:numberOfRowsInSection: are marked with the "required method" tag in Apple's documentation .

No methods are required when subclassing an NSObject (or any of their subclasses, such as UIViewController, UIView, etc. etc.).

If you create a new, let's say UIViewController, it's generally a good idea to keep the methods you find in the newly created file as a guideline/template, but you're not really required to keep any of the methods. The super class will always call the methods on itself.

Be aware, though, some methods you have to call super, like viewWillAppear, etc.

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