Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private and protected methods in Objective-C

What is the recommended way to define private and protected methods in Objective-C? One website suggested using categories in the implementation file for private methods, another suggested trailing underscores, or XX_ where XX is some project-specific code. What does Apple itself use?

And what about protected methods? One solution I read was to use categories in separate files, for example CLASS_protected.h and CLASS_protected.m but this seems like it could get very bloated. What should I do?

like image 218
Jake Petroules Avatar asked Dec 17 '22 18:12

Jake Petroules


1 Answers

There are three issues:

  1. Hiding from compiler.

    That is, making it impossible for someone else to #import something and see your method declarations. For that, put your private API into a separate header file, mark that header's role as "Private" in Xcode, and then import it in your project where you need access to said private API.

    Use a category or class extension to declare the additional methods.

  2. Preventing collisions

    If you are implementing lots of internal goop, do so with a common prefix or something that makes a collision with Apple provided (or third party) provided methods exceedingly unlikely. This is especially critical for categories and not nearly as critical for your leaf node subclasses of existing classes.

    Post the link for the site suggesting leading underscores, as they are wrong, wrong, wrong. Leading underscores are used by the system to mark private API and you can run into collisions easily enough.

  3. Hiding from the runtime.

    Don't bother. It just makes debugging / crash analysis harder and anyone determined enough to muck around at the runtime will be able to hack your app anyway.

like image 147
bbum Avatar answered Dec 28 '22 06:12

bbum