简体   繁体   中英

Objective-C message syntax

while learning Objective-C I stumbled across the following code, which I do not understand:

RootViewController *rootViewController = (RootViewController *)[self.navigationController topViewController];

As far as I understand

[self.navigationController topViewController]

is sending the message (calling the method) topViewController to self.navigationController .

Looking in the .h File I only find topViewController being a property, not a function:

@property(nonatomic,readonly,retain) UIViewController *topViewController; // The top view controller on the stack.

Can somebody explain what is happening there?

Thanks in advance!

Either syntax is fine:

[self.navigationController topViewController]

and:

self.navigationController.topViewController

The latter is calling the property's getter method, which probably looks like this:

- (UIViewController *)topViewController
{
    return _topViewController;
}

I would prefer the latter if it's been defined as a @property .

The "dot syntax" is another way of calling a method (only methods that do not have any arguments may be called this way).

So the statement:

[self.navigationController topViewController]

is actually interpreted as:

[[self navigationController] topViewController]

which means:

  • The message navigationController is sent to the object self .
  • The message topViewController is sent to the object that was returned by navigationController .

A property itself is just a fancy way of defining methods. A readonly property only provides a getter ( foo ), a read/write property also provides a setter ( setFoo: ). By default, the compiler generates these methods to access an also implicitly defined variable _foo .

A property is really a convention that means you have ivars with accessor methods, setters and getters, that meet a standard style and provides additional functionality that is derived from the conventional style.

With Objective-C 2.0 we got synthesized properties. That is the compiler will generate a lot of boilerplate code to make ivars and associated setter and getter methods for you that adhere to conventions and provide most importantly consistent memory management and KVC and KVO. (Google those separately).

It also brought the dot syntax, which is syntactic sugar, in other words the compiler interprets it the same way as corresponding bracket syntax.

Both dot and bracket syntax are transformed the same way by the compiler into the same kinds of calls.

There is no functional difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM