Pregunta

This question related to knowing something we don't know. I'm researching with "Why people don't use this"? Is any reason behind this related to specific tech? So read it carefully and give downvote or give correct answer.

We can write

NSMutableString *string = NSMutableString.string;

instead of

NSMutableString *string = [NSMutableString string];

Same as how can we write this method,

NSMutableString *string = [NSMutableString stringWithString:@"test"];

Update:

This question is not an duplicate which is little bit different. And I accept with below answers which is not recommended for good programmers. But They didn't explain Why, for What reason, programmers should avoid this? Could anyone give clear explanation about this with proper link or document?

¿Fue útil?

Solución

NSMutableString.string is a hack. It "works" for the same reason that myString.length and [myString length] produce the same result. However, since dot notation is not used with an actual property, it is an abuse of the language feature, because properties have a different semantic. For example, when you access a property multiple times, you naturally expect to get the same result, unless the state of the object has changed in between the two invocations. Since NSMutableString.string produces a new string object on each invocation, it breaks the semantic expected of the "proper" properties, bringing down the readability of your program.

Objective-C does not have a general way of calling a method with arguments using the dot notation. There feature is very specific to properties. Although theoretically you could use MyClass.xyz = abc in place of [MyClass setXyz:abc], but that would be a hack as well.

To answer your question, Objective-C does not offer a way to call [NSMutableString stringWithString:@"test"] with dot notation.

Otros consejos

It's just a syntactic sugar. string method has no arguments so it's treated like a getter, which is not in fact. stringWithString: is method with parameter, so you can't call like that.

In general, I'd not recommend using dot syntax with methods, it's confusing. Objective-C dot notation with class methods?

Update

I don't think there is any technical reason you should avoid it. It's rather in means of coding style, keeping code clean and consistent.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top