Dot notation - Does it take parameters?
Is it correct if I say that
[anIstance aMethod];
is equivalent to
anIstance.aMethod; --?
If it is the case, what about methods which take one ore more parameters?
Does the following statement
[anIstance aMethod : aParameter];
have an equivalent dot notation?
I have tried with
anIstance.aMethod : aParameter;
anIstance.aMethod(aParameter);
And they don't seem to work (compile time errors)
If there is not a way to invoke a method with parameters in dot notation wh开发者_JS百科at about the synthesized setter methods (which, as far as I know, by definition take an argument)?
If I have a synthesized property, does the following statement
anIstance.aProperty = anotherObject;
invoke the relative setter method? Or does it call the getter method?
The other answers convey the general idea, but I'd like to explicitly state that dot notation and properties are separate concepts. Dot notation is intended for setters (methods named setSomething:
that take a single parameter) and getters, and can also be used for any method that takes no parameters (though it's very poor style to use it for an action like myObject.doSomething
).
Properties are designed to declare getters and setters more easily, and even generate the code for you.
So the two concepts are related, but it's entirely possible (and not always poor style) to use dot notation with your very own getters and setters, that you wrote by hand. It's also entirely possible (and usually perfectly acceptable!) to use properties, even with getters and setters generated for you, with normal bracket syntax, and not dot notation.
But to address the original question, no, dot notation does not take parameters. It's specifically designed for use with methods that don't take parameters.
This is covered in Apple's "The Objective C Programming Language" guide:
@interface MyClass : NSObject { float value; } @property float value; @end
You can think of a property declaration as being equivalent to declaring two accessor methods. Thus
@property float value;
is equivalent to:
- (float)value; - (void)setValue:(float)newValue;
dot-notation is only valid for properties. Properties are declared with the @property declaration in Objective-C
like this:
interface MyClass {
NSString * x;
}
@property (copy) NSString *x;
implementation:
@synthesize x;
// this will generate a setter and getter method:
// - (NSString *) x {}
// - (void) setX:(NSString *)value {}
then you can use:
MyClass *obj = [[MyClass alloc] init];
obj.x = @"test";
But this only works for properties. Not for methods.
Dot notation is just syntactic sugar for properties in Objective-C, you can't use it for general method calls.
精彩评论