What is wrong with writing MyClass.alloc and MyClass.class in Objective C? - objective-c

The compiler seems to be happy, I'm happy with slightly improved readability, but Xcode's code completion doesn't particularly recognize alloc and class when invoked this way:
MyClass* object = [MyClass.alloc initWithBounty:bounty];
<...>
if ([object isKindOfClass:MyClass.class])
<...>
So I was wondering what is wrong with the above, if at all?

Well, primarily what's wrong is that dot notation is for retrieving things that are conceptually properties. alloc does not access a property of the class; it creates an object. Using it for any zero-argument method is not more readable — it's confusing.
MyClass.class is actually not problematic in that way, but there's no way to declare properties on a class and they usually aren't thought of as having properties, so the autocomplete apparently doesn't support it.

Dot notation is originally added to be used for property access. So you can use them only for
A method takes no parameter and returns single value (getter).
A method takes single parameter and returns no value (setter).
Otherwise, recent compiler will complain about it.
Anyway, I agree to #nhgrif that using dot notation on non-property method is not a good practice.

Related

objective-c difference between x.y and [x y]? [duplicate]

I am going through some walkthroughs fpr Objective-C and I got to many places where I raised my eyebrows. I would love to get them down.
Is there a fundamental difference in message sending and method calling? Objective-C lets me do both: object.message yields the same result as [object message]. I think maybe nested messages cannot be created using the dot operator strategy?
I created an NSArray object, now I am about to print results for this using an NSEnumerator:
id myObject = [object objectEnumerator];
in a while loop iterating and printing results. The type of myObject is id, which means it's resolved at runtime and not compile time. I know very clearly what kind of objects are stored in my NSArray—they are NSStrings—so by changing the type of myObject to
NSString * myObject, it works just fine. However, I experimented and found out that myObject can be of any type, be it NSString or NSArray or NSEnumerator, and any of these work just fine, perfectly iterating the NSArray object and yielding the same results.
What's up with that?
I'm not sure what kind of distinction you're trying to make between "message sending" and "method calling", since they're two ways of describing the same thing. The dot syntax is just a shortcut for calling getters and setters, that is:
[foo length]
foo.length
are exactly the same, as are:
[foo setLength:5]
foo.length = 5
You should generally only use the dot syntax when you're using getters and setters; use the square bracket syntax for all of your other method calls.
For your second question: this is how dynamic typing works. Any type declarations you put in your code are hints to the compiler; your Objective-C method calls will always work as long as the objects respond to them.
It's a distinction oriented at the person reading your code. Dot syntax indicates state (I'm accessing an ivar), method syntax indicates behavior (I'm performing some action). To the runtime, both are the same.
I think Apple's intention is to show accessors as an implementation detail you shouldn't worry about. Even when they could trigger side effects (due to some additional code in the accessor), they usually don't, so the abstraction is imperfect but worth it (IMHO). Another downside of using dot notation is that you don't really know if there is a struct or a union behind it (which unlike message sending, never trigger side effects when being assigned). Maybe Apple should have used something different from a dot. *shrugs*
I think maybe nested messages cannot be created using the dot operator strategy?
Dot notation can be used to nest calls, but consider the following:
shu.phyl.we.spaj.da
[[[[[shu]phyl]we]spaj]da]
In this case, the uglier, the better. Both are a code smell because one object is creating dependencies to another object far far away, but if use brackets to pass messages you get that extra horrible syntax from the second line, which makes the code smell easier to notice. Again, convention is to use dots for properties and brackets for methods.
1: Your terminology is incorrect. The dot operator is not "method calling", a different operation. It's just a different visual appearance for message sending. There's no difference between [x y] and x.y. The dot syntax can only take one argument though, as it's intended to be used only for property access.
2: The static (compile-time) type of an object has no effect on its behavior at runtime. Your object is still an NSEnumerator even if you're calling it something else.
1) They're both message sending, just different syntax. [object message] is traditional syntax, object.message is the "dot notation", but means exactly the same thing. You can do some kinds of nesting with dot notation, but you can't do anything with methods that take complex arguments. In general, old hand Obj-C programmers don't use dot notation except for simple accessor calls. IMHO.
2) The runtime is really smart and can figure it out on the fly. The type casting of pointers is really just a clue to the compiler to let you know when you messed up. It doesn't mean a thing (in this case) when the message is sent to the array to fetch a value.
Message sending is the preferred way of doing this. It's what the community uses and reinforces the concept of objects sending messages to one another which comes into play later when you get into working with selectors and asking an object if it responds to a selector (message).
id is basically a pointer to anything. It takes some getting used to but it's the basis for how Objective-C handles dynamic typing of objects. When NSLog() comes across the %# format specifier, it sends a description message to the object that should should replace the token (This is implemented in the superclass NSObject and can be overridden in the subclass to get the desired output).
In the future when you're doing this, you might find it easier to do something like this instead:
for (NSString *s in YourNSArrayInstance) //assuming they are NSStrings as you described
{
NSLog(#"%#", s);
}
Or even simply just:
for (NSString *s in YourNSArrayInstance) //assuming they are NSStrings as you described
NSLog(#"%#", s);
You'll learn to like message sending eventually.

Objective-C class method: dot syntax and 'class property'

While programming for iOS I encountered the following scenario:
I have a singleton class with a class method + (Store*)sharedStore. When I want to call an instance method on the singleton object, I can use dot syntax to get that object, i.e. [Store.sharedStore foo].
However, Xcode does not autocomplete 'sharedStore' after typing the dot. On the other hand, [[Store sharedStore] foo] is autocompleted!
Is there such a thing as 'class properties'? If I could turn sharedStore into a readonly property on the class, the dot syntax would gain autocompletion.
More generally speaking, Xcode simply does not autocomplete after dot syntax on anything that isn't a property, even though this is a valid way of calling a (getter) method.
Any solution, workaround, or information is appreciated.
Currently, as far as class getters go, it appears that we must either:
use this syntax in the absence of autocompletion: Store.sharedStore; or
use bracket syntax instead: [Store sharedStore].
I have not tried other editors recently (e.g. AppCode). Another editor might autocorrect the dot syntax on class getters.
Opinions vary as to what is correct, logical or readable.
Dot syntax is for accessing properties. Some people use it with instance methods that return a value and get no arguments, but it's a bad approach. All other scenarios are wrong.

What is the definition of Convenience Method in regards to Objective C?

In most languages I have dealt with, one something is called a convenience method, it means that the method does some small task that gets done very frequently, and therefore it is more convenient to use said method.
In Objective-C does this definition hold true? Or is it generally only used to describe class methods that return a prebuilt object? ex. [NSString stringWithContentsOfFile:...]
Is this just a preference thing, or are there some hard and fast definition for these terms?
Cheers,
Stefan
What you are talking about is actually more specifically a "convenience constructor" in Objective C. (Note that it's not really a constructor in the C++/Java/C# sense, it's actually an object initializer/factory method, but it seems to be the convention to call the "convenience constructors"). "Convenience constructors" in Obj C are a convention or pattern for creating a constructor/initializer/factory method for a class which takes specific parameters. This pattern also has some special conventions that you should follow (such as autoreleasing the new object within the constructor), so that your custom classes fit in well with the built-in types.
See this page (a little way down) for more info: http://macdevcenter.com/pub/a/mac/2001/07/27/cocoa.html?page=3
As for "convenience method," this specific term doesn't have any special meaning in Objective C. You can create any type of convenience method in Obj C, and there is no expectation about what it should or should not do. It's only "convenience constructor" that has a special meaning.
So far as I know, "convenience method" means basically what you defined it to mean here: a single method or function which replaces a more complicated series of invocations because of its frequency of use.
In Objective-C, the "ordinary" way to create a new instance is something along the lines of NSSomething * mySomething = [[[NSSomething alloc] initWithParam:... andParam:...] autorelease]. Many classes provide convenience constructors which simplify these three steps (in fact, in most cases, they probably literally do exactly the same thing, but wrapped behind a class method call).

Objective-C Property Access

What is the difference in accessing an objects properties or methods via foo.property to [foo property]?
Nothing! Dot-notation is "syntactic sugar" introduced in Objective-C 2.0. In fact, the compiler converts foo.property to [foo property] during compile-time, so they compile to exactly the same thing.
It's simply a matter of which you prefer.
At compile time they're treated the same, but one benefit of using dot notation to handle properties is that while coding, after placing the "." code completion/code window will only show valid properties as suggestions whereas using brackets will show all methods.

Dot notation vs. message notation for declared properties [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
We now have the "dot" notation for properties. I've seen various back and forths about the merits of dot notation vs. message notation. To keep the responses untainted I'm not going to respond either way in the question.
What is your thought about dot notation vs. message notation for property accessing?
Please try to keep it focused on Objective-C - my one bias I'll put forth is that Objective-C is Objective-C, so your preference that it be like Java or JavaScript aren't valid.
Valid commentary is to do with technical issues (operation ordering, cast precedence, performance, etc), clarity (structure vs. object nature, both pro and con!), succinctness, etc.
Note, I'm of the school of rigorous quality and readability in code having worked on huge projects where code convention and quality is paramount (the write once read a thousand times paradigm).
Do not use dot for behavior. Use dot to access or set attribute like stuff, typically attributes declared as properties.
x = foo.name; // good
foo.age = 42; // good
y = x.retain; // bad
k.release; // compiler should warn, but some don't. Oops.
v.lockFocusIfCanDraw; /// ooh... no. bad bad bad
For folks new to Objective-C, I would recommend not using the dot for anything but stuff declared as #property. Once you have a feel for the language, do what feels right.
For example, I find the following perfectly natural:
k = anArray.count;
for (NSView *v in myView.subviews) { ... };
You can expect that the clang static analyzer will grow the ability to allow you to check that the dot is being used only for certain patterns or not for certain other patterns.
Let me start off by saying that I started programming in Visual/Real Basic, then moved on to Java, so I'm fairly used to dot syntax. However, when I finally moved to Objective-C and got used to brackets, then saw the introduction of Objective-C 2.0 and its dot syntax, I realized that I really don't like it. (for other languages it's fine, because that's how they roll).
I have three main beefs with dot syntax in Objective-C:
Beef #1: It makes it unclear why you might be getting errors. For example, if I have the line:
something.frame.origin.x = 42;
Then I'll get a compiler error, because something is an object, and you can't use structs of an object as the lvalue of an expression. However, if I have:
something.frame.origin.x = 42;
Then this compiles just fine, because something is a struct itself that has an NSRect member, and I can use it as an lvalue.
If I were adopting this code, I would need to spend some time trying to figure out what something is. Is it a struct? Is it an object? However, when we use the bracket syntax, it's much clearer:
[something setFrame:newFrame];
In this case, there is absolutely no ambiguity if something is an object or not. The introduction of ambiguity is my beef #1.
Beef #2: In C, dot syntax is used to access members of structs, not call methods. Programmers can override the setFoo: and foo methods of an objects, yet still access them via something.foo. In my mind, when I see expressions using dot syntax, I'm expecting them to be a simple assignation into an ivar. This is not always the case. Consider a controller object that mediates an array and a tableview. If I call myController.contentArray = newArray;, I would expect it to be replacing the old array with the new array. However, the original programmer might have overridden setContentArray: to not only set the array, but also reload the tableview. From the line, there's no indication of that behavior. If I were to see [myController setContentArray:newArray];, then I would think "Aha, a method. I need to go see the definition of this method just to make sure I know what it's doing."
So I think my summary of Beef #2 is that you can override the meaning of dot syntax with custom code.
Beef #3: I think it looks bad. As an Objective-C programmer, I'm totally used to bracket syntax, so to be reading along and see lines and lines of beautiful brackets and then to be suddenly broken with foo.name = newName; foo.size = newSize; etc is a bit distracting to me. I realize that some things require dot syntax (C structs), but that's the only time I use them.
Of course, if you're writing code for yourself, then use whatever you're comfortable with. But if you're writing code that you're planning on open sourcing, or you're writing something you don't expect to maintain forever, then I would strong encourage using bracket syntax. This is, of course, just my opinion.
Blog post against dot syntax: https://bignerdranch.com/blog/dot-notation-syntax/
Rebuttal to above post: http://eschatologist.net/blog/?p=226 (with original article in favor of dot syntax: http://eschatologist.net/blog/?p=160)
I'm a new Cocoa/Objective-C developer, and my take on it is this:
I stick to the messaging notation, even though I started with Obj-C 2.0, and even though the dot notation is more familiar feeling (Java is my first language.) My reason for this is pretty simple: I still don't understand exactly why they added the dot notation to the language. To me it seems like an unnecessary, "impure" addition. Although if anyone can explain how it benefits the language, I'd be happy to hear it.
However, I consider this a stylistic choice, and I don't think there is a right or wrong way, as long as it's consistent and readable, just as with any other stylistic choice (like putting your opening curly brace on the same line as the method header or the next line).
Objective-C dot notation is a syntactic sugar that is translated to normal message passing, so under the hood changes nothing and makes no difference at runtime. Dot notation it is absolutely not faster than message passing.
After this needed little preamble here's pros and cons seen by me :
Dot notation pros and cons
pros
readability : dot notation is easier to read than nested brackets massages passing
It simplifies interaction with Attributes and Properties: using dot notation for properties and message notation for methods you can achieve separation of state and behavior at the synthax level
It is possible to use compound assignment operator (1).
using the #property and dot notation the compiler do a lot of work for you, it can generate code for good Memory Management when getting and setting the property; this is why dot notation is suggested by Apple itself official guides.
cons
Dot notation is allowed only for access to a declared #property
Since Objective-C is a layer above standard C(language extension), the dot notation doesn’t really make clear if the accessed entity is a an object or a struct. Often, it looks like you are accessing properties of a struct.
calling a method with the dot notation you lose named parameters readability advantages
when mixed message notation and dot notation seems like you are coding in two different languages
Code Examples :
(1)Compound operator usage code example :
//Use of compound operator on a property of an object
anObject.var += 1;
//This is not possible with standard message notation
[anObject setVar:[anObject var] + 1];
Using the style of a language, consistent with the language itself, is the best advice here. However, this isn't a case of writing functional code in an OO system (or vice versa) and the dot notation is part of the syntax in Objective-C 2.0.
Any system can be misused. The existence of the preprocessor in all C based languages is enough to do really quite weird things; just look at the Obfuscated C Contest if you need to see exactly how weird it can get. Does that mean the preprocessor is automatically bad and that you should never use it?
Using the dot syntax for accessing properties, which have been defined as such in the interface, is open to abuse. The existence of abuse in potentia shouldn't necessarily be the argument against it.
Property access may have side-effects. This is orthogonal to the syntax used to acquire that property. CoreData, delegation, dynamic properties (first+last=full) will all necessarily do some work under the covers. But that would be confusing 'instance variables' with 'properties' of an object. There's no reason why properties should necessarily need to be stored as-is, especially if they can be computed (e.g. length of a String, for example). So whether you use foo.fullName or [foo fullName] there's still going to be dynamic evaluation.
Lastly, the behaviour of the property (when used as an lvalue) is defined by the object itself, like whether a copy is taken or whether it is retained. This makes it easier to change the behaviour later - in the property definition itself - rather than having to re-implement methods. That adds to the flexibility of the approach, with the resulting likelihood of less (implementation) errors occurring. There's still the possibility of choosing the wrong method (i.e. copy instead of retain) but that's an architectural rather than implementation issue.
Ultimately, it boils down to the 'does it look like a struct' question. This is probably the main differentiator in the debates so far; if you have a struct, it works differently than if you have an object. But that's always been true; you can't send a struct a message, and you need to know if it's stack-based or reference/malloc based. There are already mental models which differ in terms of usage ([[CGRect alloc] init] or struct CGRect?). They've never been unified in terms of behaviour; you need to know what you're dealing with in each case. Adding property denotation for objects is very unlikely to confuse any programmer who knows what their data types are; and if they don't, they've got bigger problems.
As for consistency; (Objective-)C is inconsistent within itself. = is used both for assignment and equality, based on lexical position in the source code. * is used for pointers and multiplication. BOOLs are chars, not bytes (or other integer value), despite YES and NO being 1 and 0 respectively. Consistency or purity isn't what the language was designed for; it was about getting things done.
So if you don't want to use it, don't use it. Get it done a different way. If you want to use it, and you understand it, it's fine if you use it. Other languages deal with the concepts of generic data structures (maps/structs) and object types (with properties), often using the same syntax for both despite the fact that one is merely a data structure and the other is a rich object. Programmers in Objective-C should have an equivalent ability to be able to deal with all styles of programming, even if it's not your preferred one.
I've mostly been raised in the Objective-C 2.0 age, and I prefer the dot notation. To me, it allows the simplification of code, instead of having extra brackets, I can just use a dot.
I also like the dot syntax because it makes me really feel like I'm accessing a property of the object, instead of just sending it a message (of course the dot-syntax really does translate into message sending, but for the sake of appearances, the dot feels different). Instead of "calling a getter" by the old syntax, it really feels like I'm directly getting something useful from the object.
Some of the debate around this is concerned with "But we already have dot-syntax, and it's for structs!". And that's true. But (and again, this is just psychological) it basically feels the same to me. Accessing a property of an object using dot-syntax feels the same as accessing a member of a struct, which is more or less the intended effect (in my opinion).
****Edit: As bbum pointed out, you can also use dot-syntax for calling any method on an object (I was unaware of this). So I will say my opinion on dot-syntax is only for dealing with properties of an object, not everyday message sending**
I use it for properties because
for ( Person *person in group.people){ ... }
is a little easier to read than
for ( Person *person in [group people]){ ... }
in the second case readability is interupted by putting your brain into message sending mode, whereas in the first case it is clear you are accessing the people property of the group object.
I will also use it when modifying a collection, for instance:
[group.people addObject:another_person];
is a bit more readable than
[[group people] addObject:another_person];
The emphasis in this case should be in the action of adding an object to the array instead of chaining two messages.
I much prefer the messaging syntax... but just because that is what I learned. Considering a lot of my classes and what not are in Objective-C 1.0 style, I wouldn't want to mix them. I have no real reason besides "what I'm used to" for not using the dot syntax... EXCEPT for this, this drives me INSANE
[myInstance.methodThatReturnsAnObject sendAMessageToIt]
I don't know why, but it really infuriates me, for no good reason. I just think that doing
[[myInstance methodThatReturnsAnObject] sendAMessageToIt]
is more readable. But to each his own!
Honestly, I think it comes down to a matter of style. I personally am against the dot syntax (especially after just finding out that you can use it for method calls and not just reading/writing variables). However, if you are going to use it, I would strong recommend not using it for anything other than accessing and changing variables.
One of the main advantages of object-oriented programming is that there is no direct access to internal state of the objects.
Dot syntax seems to me to be an attempt to make it look and feel as though state is being accessed directly. But in truth, it's just syntactic sugar over the behaviors -foo and -setFoo:. Myself, I prefer to call a spade a spade. Dot syntax helps readability to the extent that code is more succinct, but it doesn't help comprehension because failing to keep in mind that you're really calling -foo and -setFoo: could spell trouble.
Synthesized accessors seem to me to be an attempt to make it easy to write objects in which state is accessed directly. My belief is that this encourages exactly the kind of program design that object-oriented programming was created to avoid.
On balance, I would rather dot syntax and properties had never been introduced. I used to be able to tell people that ObjC is a few clean extensions to C to make it more like Smalltalk, and I don't think that's true any more.
In my opinion, the dot syntax makes Objective-C less Smalltalk-esque. It can make code look simpler, but adds ambiguity. Is it a struct, union, or object?
Many people seems to be mixing up 'properties' with 'instance variables'.
The point of the properties is to make it possible to modify the object without having to know its internals, I think. The instance variable is, most of the time, the 'implementation' of a property (which in turn is the 'interface'), but not always: sometimes a property does not correspond to an ivar, and instead it calculates a return value 'on the fly'.
That's why I believe the idea that "the dot syntax tricks you into thinking you're accessing the variable so it's confusing" is wrong. Dot or bracket, you shouldn't make assumptions about the internals: it's a Property, not an ivar.
I think I might switch to messaging instead of dot notation because in my head object.instanceVar is just instanceVar that belongs to object, to me it doesn't look at all like a method call, which it is, so there could be things going on in your accessor and whether you use instanceVar or self.instanceVar could have much more of a difference than simply implicit vs. explicit. Just my 2¢.
The dot notation tries to make messages look like accesses to a member of a struct, which they are not. Might work fine in some cases. But soon someone will come up with something like this:
NSView *myView = ...;
myView.frame.size.width = newWidth;
Looks fine. But is not. It's the same as
[myView frame].size.width = newWidth;
which doesn’t work. The compiler accepts the first, but rightfully not the second. And even if it emitted an error or warning for the first this is just confusing.
Call me lazy but if I had to type a single '.' vs. two [ ] each time to get the same results I would prefer a single . I hate verbose languages. The () in lisp drove me nuts. Elegant language such as mathematics are concise and effective, all others fall short.
Use dot notation (whenever you can)
On instance methods returning some value
Do not use dot notation
On instance methods returning void, on init methods or on Class method.
And my personal favorite exception
NSMutableArray * array = #[].mutableCopy;
I personally don't use dot-notation at all in code. I only use it in CoreData KVC binding expression when required.
The reason for not using them in code for me is that the dot-notation hides the setter semantics. Setting a property in dot-notation always looks like assignment regardless of the setter semantics (assign/retain/copy). Using the message-notation makes it visible that the receiving object has control over what happens in the setter and underlines the fact the those effects need to be considered.
I'm still considering whether I might want to use dot-notation when retrieving the value of a KVC compliant or declared property because it admittedly is a bit more compact and readable and there are no hidden semantics. Right now I'm sticking with message-notation for sake of consistency.
OK, dot notation in Objective-C looks strange, indeed. But I still can't do the following without it:
int width = self.frame.size.width;
Works fine, but:
int height = [[[self frame] size] height];
Gives me "Cannot convert to a pointer type". I'd really like to keep my code looking consistent with message notation, though.
This is a great question and I see many different answers to this. Although many have touched upon the topics, I will try to answer this from a different angle (some might have done it implicitly):
If we use the 'dot' notation, the resolution of the target for the method is done at compile time. If we use message passing, the resolution of the target is deferred to run-time execution. If the targets are resolved at compile time, the execution is faster, since resolving the targets at the run-time includes a few overheads. (Not that the time difference will matter much). Since we have defined the property in the interface of the object already, there is no point in differing the resolution of the target for a property to run-time and hence dot-notation is the notation that we should use for accessing property.