Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline accessor (getter/setter) methods in Objective-C

Data encapsulation, or as I like to call it, Who owns it and who needs to know about it, makes up a lot of object-oriented programming. The who needs to know is often satisfied by accessor methods, but these get to be pretty expensive if they all result in an objc_msgsend just to read a variable. C++ answers the problem with inline methods - use the "inline" keyword before the definition, or define the method within the class declaration, and the compiler puts the accessor code within the caller's code, saving the overhead associated with an actual function call.

class IntWrapper {
public:
   int getInt() { return anInt; }
protected:
   int anInt;
};

Similar syntax is rewarded by a complier error in Objective-C. Having searched the language guides in Xcode ("[Object-Oriented] Programming with Objective-C"), I don't see any relevant reference to "inline" of a method. Is there such thing as inline in Objective-C? Is it called something else? If anyone could point me to the documentation that references inline, much appreciated.

Using the simple test code:

@interface ClassA : NSObject
{
   int anInt;
}
- (int) anInt;
@end

@implementation ClassA
- (int) anInt { return anInt; }
@end

and looking at the assembly of the code that uses it, it looks like about 25 instructions.

like image 937
user3308886 Avatar asked Feb 03 '26 21:02

user3308886


1 Answers

All Objective-C methods are dispatched dynamically. They can be overridden by subclasses. They can even be replaced at runtime ("swizzled") by the Objective-C runtime API.

In some ways, they are similar to virtual methods in C++.

As such they can't be inlined.

By the way, the technique you cite violates the principle you cite ("Who owns it and who needs to know about it?"). Putting the implementation in the class declaration exposes implementation detail to clients who don't need to know it. Furthermore, the compiler inlining the code into clients prevents that implementation from changing without a recompile, which is the fragile base class problem. Modern Objective-C avoids the fragile base class problem, which means a framework class can change what instance variables it has without breaking clients.

like image 156
Ken Thomases Avatar answered Feb 06 '26 12:02

Ken Thomases



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!