Functional call instead of self-service - when to use what?

In Objective-C, when I want to call a routine, I send a message to an object, for example:

[self mySubroutine:myParameter];

There is (negligible?) Performance, so I can just use the C-style function call:

mySubroutine(myParameter);

Then the implementation of the latter will be outside the context of the @implementation classes.

Isn't this a no-no? Is this common? Is there any best practice on this?

+7
source share
2 answers

Please note that they are not necessarily equivalent. Because -mySubroutine is an instance method, it probably needs to access that instance. In this case, your mySubroutine() function should have another parameter for the instance.

In general, use the method. If you are concerned about performance, 1 you can always get the IMP method and use it as a function instead of the standard Objective-C messaging infrastructure.

However, some disadvantages of using functions are:

  • They cannot be overridden by subclasses;
  • Lack of introspection (when using the runtime to get a list of methods declared by the Objective-C class, the functions arent listed);
  • They cannot be used as accessors / mutators of declared properties;
  • They arent visible Keyword Coding ;
  • They cannot be used directly to forward Objective-C messages;
  • They cannot be used directly in cases where the Cocoa API expects a selector (for example, when using NSTimer ).

Some benefits of using features:

  • They cannot be overridden by subclasses (if you want to prevent this);
  • Lack of introspection (if you want to prevent this);
  • They can be embedded;
  • They can have a file area ( static ), preventing code from other files from accessing them.

1 When you determined that the messaging framework is actually a bottleneck. It happens; for example, some Apple audio examples do not use Objective-C for audio processing.

Edit: Based on OPs comment, another advantage of functions is that they arent necessarily associated with the class. If the calculation of the approximate value for the sine of the angle does not depend on the Objective-C instance, then there is no need to make it a method - the function is better suited.

+7
source

It may be worth using the functions of a static utility, for example, in the maths library.

In general, if you need methods that affect the state of an object, the C approach will not be very useful, since you will not have implicit access to self unless you explicitly pass it as a parameter.

You may also encounter namespace problems. Using Objective-C, different classes can share method names, with the c-approach, all your functions will require different signatures.

Personally, I will always use Objective-C methods, the difference in performance will be insignificant.

+2
source

All Articles