Question

I've just got the clear explanation of what "->" notation is about here: Dot (".") operator and arrow ("->") operator use in C vs. Objective-C

But I still don't understand what are really the use cases of this notation in Objective-C?

Here is the example of what I'm talking about: https://github.com/gnustep/gnustep-base/blob/master/Source/NSOperation.m - why all these strings like internal->lock are written there - why not just use ivars or dot-notation?


Related topic: Performance of object_setClass() instead of assigning isa pointer.

Was it helpful?

Solution

From your question, it's not clear if you understand what the -> operator does.

That example in the GNUStep NSOperation source is using an ivar. That's what the -> operator does — it dereferences the pointer and accesses the named member.

As for "Why not use dot notation?" The obvious answer would be that they didn't want to go through an accessor. Going through an accessor is slower than direct access and has no real benefit in a case like this where we're just working with "dumb" internal state.

So when should you use it in your Objective-C code? Mainly when you're accessing a struct through a pointer. There is seldom a need to access another object's instance variables directly. If you do, that code is the exception, not the rule.

OTHER TIPS

May be in this case.I saw an example in apple's Reachability.m file.Here it is:

@implementation Reachability
{
    SCNetworkReachabilityRef _reachabilityRef;
}

+ (instancetype)reachabilityWithHostName:(NSString *)hostName
{
    ...
    if (reachability != NULL)
    {
        returnValue= [[self alloc] init];
        if (returnValue != NULL)
        {
            returnValue->_reachabilityRef = reachability;
        }
        ...
    }
    return returnValue;
}

So you can use it to call an global variable by an object in a class method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top