Undeclared c functions and methods

In the solutions for this chapter (from the Big Nerd Ranch site), there are several C like functions defined in the .m file outside of the implementation file. I didn’t know we could do such a thing before reading those solutions. So that was very helpful to see.

After doing some experimenting, it appears that you can also put those functions inside the @implementation section of the .m file. The only difference I could see was that when putting them there, you can put them in any order. But if you put them outside of the @implementation section, if one function depends on another function, it had to come afterwards. Now all of this is if you don’t declare them in the .h file.

So what is a good reason to leave these functions outside of the @implementation section? Are using such functions a common thing to do? It appears you don’ have direct access to self or any ivars. So that also makes me wonder about making them undeclared methods instead. Is it because using C functions is more efficient?

Also, is it a good practice to mark these C functions as static unless you want to be able to use them in main? It appears that you can call them in main (but you get an implicit declaration warning) unless you declare them in the .h file.

This also led me to consider methods that are not defined in the .h file. I don’t see any difference in just adding them in the @implemenation section in the .m file with or without a class intersection (in other words, declaring them in @interface ClassName () section but in the .m file). Either way, the order you put them in doesn’t seem to matter. What is the modern day convention?

They are all good observations.

Given that Objective-C is a super set of the C language, your observations should not come as a surprise.

As for putting the C functions inside of an implementation block, there is no harm in doing that. However, it is probably better to put only Objective-C is methods (class and instance methods in there and keep the C-functions outside the block and mark them as static unless they are going to be accessed from outside the containing object module.

You can actually look at what’s going with those functions by looking at the symbols inside an executable OSX program or an object module by using the nm command from a Terminal window.

1 Like