سؤال

I know this idea completely breaks encapsulation, but say I have the following class extension:

@interface MyClass () {
    int reallyImportantIvar;
}
// ...
@end

Normally, the class behaves like it should inside the Objective-C layer - sending and receiving messages, etc. However there is one ('public') subroutine where I need the best possible performance and very low latency, so I would prefer to use a C method. Of course, if I do, I can no longer access reallyImportantIvar, which is the key to my performance-critical task.

It seems I have two options:

  1. Make the instance variable a static variable instead.
  2. Directly access the instance variable through the Objective-C runtime.

My question is: is Option 2 even possible, and if so, what is its overhead? (E.g. Am I still looking at an O(n) algorithm to look up a class's instance variables anyway?)

هل كانت مفيدة؟

المحلول 3

The Objective-C runtime includes the object_getInstanceVariable() function. I believe that's what you're looking for. I haven't checked in detail, but I don't believe there is any big difference between accessing it that way and the normal way.

نصائح أخرى

Actually, if the definition of the C function is within the @implementation block of the class, then it can access private ivars on that class via the usual object->someIvar notation. So while you can use the runtime to access this, I don't think you need to. Just implement the function within the @implementation block of the class in question, and you should be just fine.

Another alternative is to declare the ivar as @package or @public. Then code outside your class's implementation that can #include that class extension can use the ivar.

@public allows any code to do so. @package limits the scope to the same binary as the class's implementation, which is usually appropriate when writing a shared library.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top