Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c calling method without []

Tags:

objective-c

Whats the difference between the method calls:
time.text = s;
[time setText:s];

if any?

The tutorial from https://developer.apple.com/library/ios/#referencelibrary/GettingStarted/RoadMapiOS/JumpRightIn/iPhone101/Articles/06_ImplementingController.html uses both:
- (IBAction)changeGreeting:(id)sender {
self.userName = self.textField.text;
NSString *nameString = self.userName;
if ([nameString length] == 0) {
nameString = @"World";
}
NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString];
self.label.text = greeting;
}

When to use what?
Im relative new to Objective-C if that matters.

like image 776
hub Avatar asked May 25 '26 00:05

hub


2 Answers

The other answers have some merit, but also have some things confused. Here's my take:

The bracket notation is the general syntax for sending messages / invoking methods.

There are all sorts of different methods. One particular kind of methods are accessors – setters and getters for properties.

The dot syntax is an alternative form for invoking accessors. It's a somewhat newer style, just added to the language in the last several years. Using it is purely optional, if you find it clearer and less verbose. The difference is purely cosmetic. Using dot syntax is identical to invoking an accessor, either a getter or setter depending on how the subexpression is used within the larger expression.

like image 164
Ken Thomases Avatar answered May 27 '26 15:05

Ken Thomases


AFAIK They both are same...

time.text = s;

internally performs... [time setText:s];

The earlier is just the dot notation which some people find more easier to use and is quite prevalent in other languages.

EDIT:

One more thing to add is I am only referring to properties here, since only they have getters and setters. Method calling is a different thing as there you can pass more parameters.

like image 40
Ankit Srivastava Avatar answered May 27 '26 16:05

Ankit Srivastava



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!