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, others suggested trailing underscores or XX_, where XX is some code for a specific project. What is the use of Apple itself?

What about protected methods? One solution that I read was to use categories in separate files, like CLASS_protected.h and CLASS_protected.m, but it looks like it can get very bloated. What should I do?

+4
source share
2 answers

There are three problems:

  • Hiding from the compiler.

    That is, it makes it impossible for someone else to #import something and see the declarations of your method. To do this, put your private API in a separate header file, mark the role of the header as "Private" in Xcode, and then import it into your project where you need access to the specified private API.

    Use a category or class extension to declare additional methods.

  • Collision avoidance

    If you are implementing a lot of internal errors, do it with a common prefix or something that makes a collision with provided by Apple (or third-party) provided methods that are extremely unlikely. This is especially important for categories and not so critical for your subclasses of node existing classes.

    Send a link to the site offering leading underscores as they are incorrect, incorrect, and incorrect. Leading underscores are used by the system to indicate a private API, and you can easily run into conflicts.

  • Hiding from the runtime.

    Do not worry. It just makes debugging / crash analysis more difficult, and anyone who is tuned enough to damp around at runtime will be able to crack your application anyway.

+11
source

There are no β€œreal” private methods in Objective-C, since the runtime will allow access to any method in any class through public APIs using their string names.

I never make separate interface files for "private" methods, and let the compiler complain if I try to use these any of these methods outside the scope of the file.

XX_ seems to be a special means of creating a pseudo-namespace. The idea is to read Apple documents and documents of any frameworks that you could use at any time in the future, and choose the XX prefix that none of these others will ever use.

+1
source

Source: https://habr.com/ru/post/1336721/


All Articles