Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected methods in Objective-C

Tags:

objective-c

What is the equivalent to protected methods in Objective-C? I want to define methods which only the derived classes may call/implement.

like image 788
LK. Avatar asked Sep 16 '10 10:09

LK.


People also ask

What methods of an object class are protected?

There are two protected methods in Object : clone() and finalize() . finalize() is not intended to be called by client code, but may be overridden by subclasses - thus, it is protected.

What is a protected method?

A protected method is like a private method in that it can only be invoked from within the implementation of a class or its subclasses. It differs from a private method in that it may be explicitly invoked on any instance of the class, and it is not restricted to implicit invocation on self .

Can we call protected method using object?

The method displayed in class A is protected and class B is inherited from class A and this protected method is then accessed by creating an object of class B.

Can we declare protected method in public class?

Notes: You cannot declare a class as protected . Only the methods or fields within a class can have this access modifier.


1 Answers

You can simulate protected and private access to methods by doing the following:

  • Declare your private methods in a class extension (i.e. a unnamed category declared near the top of the class' .m file)
  • Declare your protected methods in a Subclass header – Apple uses this pattern with respect to UIGestureRecognizer (see documentation and reference to UIGestureRecognizerSubclass.h)

These protections are not, as Sachin noted, enforced at runtime (as they are in Java, for example).

like image 167
Brian Westphal Avatar answered Nov 01 '22 20:11

Brian Westphal