Home > Back-end >  What is the difference between "foo.bar" and "[foo bar]" in objective C?
What is the difference between "foo.bar" and "[foo bar]" in objective C?

Time:10-11

I'm following Apple's Objective C MetalKit guide, and this line of code appears here:

MTLRenderPassDescriptor *renderPassDescriptor = view.currentRenderPassDescriptor;

Is there a difference between using view.currentRenderPassDescriptor; and [view currentRenderPassDescriptor];? I've always seen the second option and neither are giving me errors or different results, but it seems strange that they would have both syntax options available for the same purpose.

CodePudding user response:

The dot syntax is syntactic sugar, merely a newer, more concise, syntax that they subsequently added to the language. The dot syntax and the square brackets are functionally equivalent.

See Dot Syntax Is a Concise Alternative to Accessor Method Calls from Programming with Objective-C:

As well as making explicit accessor method calls, Objective-C offers an alternative dot syntax to access an object’s properties.

Dot syntax allows you to access properties like this:

NSString *firstName = somePerson.firstName;
somePerson.firstName = @"Johnny";

Dot syntax is purely a convenient wrapper around accessor method calls. When you use dot syntax, the property is still accessed or changed using the getter and setter methods mentioned above:

  • Getting a value using somePerson.firstName is the same as using [somePerson firstName]
  • Setting a value using somePerson.firstName = @"Johnny" is the same as using [somePerson setFirstName:@"Johnny"]

This means that property access via dot syntax is also controlled by the property attributes. If a property is marked readonly, you’ll get a compiler error if you try to set it using dot syntax.

  • Related