Is it OK to use dot syntax to call methods? - objective-c

I'm trying to learn how to develop using objective C and I read on this book that to access an ivar from a class using dot syntax (obj.var) you must implement these vars using #properties, however I've tried using this kind of access without defining #properties for these vars and it seemed to work normally.
How does this kind of access works ? Is it a good practice to use it like it's in Java ?
Example:
ComplexNumber *c1 = [[ComplexNumber alloc]init];
c1.realPart = 3;
c1.imaginaryPart = 2;
ComplexNumber's methods:
- (double)modulus;
-(void)setRadius:(double)aRadius phase:(double)aPhase;
-(void)print;
-(double)realPart;
-(double)imaginaryPart;
-(void)setRealPart:(double)value;
-(void)setImaginaryPart:(double)value;

A property is just a promise that the class implements certain methods. The dot syntax is simply translated into calls to methods with the appropriate name, depending on what the code is doing:
b = a.foo; // becomes 'b = [a foo];'
a.foo = b; // becomes '[a setFoo:b];'
So you can actually get away with using dot syntax to call methods even when those methods aren't properties. That can be sort-of okay if the method represents something that works like a property, such as accessing the length method of an array:
len = myArray.length // becomes 'len = [myArray length];'
But mostly you shouldn't do it. It takes something that's not a property and makes it look like a property. It might work, but it's going to confuse people who look at the code (including the future you). You definitely shouldn't use it to call methods that have side effects because property accessors aren't expected to have side effects.

No its not a good practice, you technically can access zero argument methods using dot syntax but now Xcode will warn you about doing this. This is against Apple's coding guidelines.
Bracket syntax should be used for calling methods.

Related

Instance method not found warning, but working

In my implementation model, I need to have some differents files, with some similar methods. Also, I gather objects of differents types in a NSMutableArray, and try to call my similar method like this:
[[ArrayOfViews objectAtIndex:i] myMethodWithInt:'number' andExample:'char'];
But it gives me a warning:
Instance method '...' not found (return type defaults to 'id')
My code works, but should I fix this warning or not?
You should introduce the type:
MONType * obj = [ArrayOfViews objectAtIndex:i];
Then call the method using the typed variable:
[obj myMethodWithInt:<#number#> andExample:<#char#>];
It could be complaining for a number of reasons. Introducing the type will either fix those categories of issues, or at least give you a more useful warning. Specifically, the compiler does not see a declaration of the instance method -myMethodWithInt:andExample:.
You've likely either not imported a header, or declared the method so that it is visible in the translation.
My code works, but should I must fix this warning or not ?
Maybe. Sometimes it will 'work'. This is equivalent to C89's missing function prototypes, which were phased out because of all the issues they caused. So implicit parameters and return types can work if the parameters and return type is id compatible (including NSObject subclasses). But if it is not a match, then you should expect undefined behavior. You can avoid all this and introduce meaningful type checking by using the appropriate imports and declarations in your programs, and by introducing the type as illustrated above. This is useful because the compiler will save you from a ton of silly mistakes as you work and as your codebases evolve.
It's probably just a case of not having the method declared before the call. Try adding the method declaration to the interface section of the class.
Adding a typecast to your objectAtIndex call with get rid of the warning. This isn't a big issue, but it's good practice to typecast returns from an NSArray.
Basically:
YourObjectType *yourObject = (YourObjectType*)[ArrayOfViews objectAtIndex:i];
[yourObject myMethodWithInt:'number' andExample:'char'];
You need to add an #import statement for the header that declares the method or methods you want to call.

ObjC protocols potentially useless

In ObjC we can use protocols to restrict an id behavior, so we can declare something like
-(void)aMethod:(id<aProtocol>)aVar which works very well until we provide a value or a non-id variable as aVar, but this gets completely broken since we can pass a generic id variable delcared without protocols specifiers... Is this normal? Is there any workaround? Am I missing something?
Just use id less, and declare variables and parameters using the correct types, where possible. That is to say: don't pass ids around. If you are implementing a collections class (for example), then id's often useful.
My approach is to specify types, and introduce that type as local as possible in the source. So I omit id and add the type, and when (for instance) I take a reference from a collection, I create a variable:
MONType<MONProtocol>* thing = [array objectAtIndex:idx];
// now thing is correctly typed. use thing.
Similarly, if I have an id parameter, I declare a new variable:
- (IBAction)someAction:(id)sender
{
NSButton * button = sender;
// now use button, not sender
Protocols are extremely useful. Very often, better/cleaner than subclassing.
You're missing the understanding that types in Objective-C are determined at runtime, not compile time. Just because you say that an object will be of type id<aProtocol> does not mean that at runtime it is guaranteed to be so.
The idea of specifying something as id<aProtocol> is to aid you as a developer and people using your code. It aids you as a developer because the compiler will warn (or error under ARC) if you attempt to call a method on something that the compiler can determine it doesn't think exists on instances of its supposed type (excluding forwarding which could mean an instance responds to something the compiler cannot determine). It aids people using your code as it tells them the contract that they should adhere to when interfacing with your code.
So, in your question you say that:
but this gets completely broken if we pass a generic id variable delcared without protocols specifiers
Well, the compiler would warn and tell you that you're trying to pass something that does not conform to that protocol, except for the case of passing id. That's why you generally should try to type things more precisely than just id.
If you have a method defined like so:
- (void)aMethod:(id<aProtocol>)aVar
Then aVar could be of type SomeSubclass where that is defined like so:
#interface SomeSubclass : NSObject <aProtocol>
And you could then use aMethod like this:
SomeSubclass *obj = [SomeSubclass new];
[other aMethod:obj];
I (FINALLY) found out that using Objective-C++ is the way to go. Let's suppose I want to be able to pass NSString or NSNumber (instead of a too much generic id and instead of using protocols which become useless passing id values): well, I can create a C++ class having two distinct constructors, one for each ObjC class, so passing id values cannot be done anymore (almost directly). For example, let's take a look at
class NSStringOrNSNumber{
public:
NSStringOrNSNumber(NSString *);
NSStringOrNSNumber(NSNumber *);
};
The great advantage is that methods/functions taking a NSStringOrNSNumber parameter can get NSString/NSNumber values DIRECTLY, since the constructor acts as an implicit cast. In other words, if we have
void aFunction(NSStringOrNSNumber param);
the following calls are perfectly valid:
aFunction(#"Hello!");
aFunction(#25);
The only (little) downside is that we need the class to implement a function if we want to get back the value passed to the constructor.
Using a C++ class constructor to get something like id<NSCoding> is still better the using id<NSCoding> directly: in fact, if we do the following
#class classOne, classTwo;
class NSCodingClass{
private:
NSCodingClass(classOne *);
NSCodingClass(classTwo *);
public:
NSCodingClass(id<NSCoding>);
}
we won't be able to pass a generic id as a parameter (since it would be ambiguous: the compiler cannot know which constructor to call among the two private ones)

What is the -> operator doing in -copyWithZone:? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Arrow operator (->) usage in C
Dot (“.”) operator and arrow (“->”) operator use in C vs. Objective-C
I'm a newbie looking at a freeware/open-source program last updated in 2008, and I don't recognize the -> in the following notation:
- (id)copyWithZone:(NSZone *)zone
{
GFIPGeniusItem * newItem = [[[self class] allocWithZone:zone] init];
newItem->_stringValue = [_stringValue copy];
newItem->_imageURL = [_imageURL copy];
newItem->_webResourceURL = [_webResourceURL copy];
newItem->_speakableStringValue = [_speakableStringValue copy];
newItem->_soundURL = [_soundURL copy];
return newItem;
}
I'm assuming it's allowing some sort of shortcut, but I'd love to specifically what it does.
It's a way to directly access an instance variable within an ObjC object from outside that object. (The syntax and -> is borrowed from C structs, behaving as if the reference were a pointer-to-structure).
This access mechanism is almost vestigial at this point, and very uncommonly seen in modern ObjC code, because good encapsulation requires the use of accessors and properties, not touching instance variables directly. It's legitimate in some very special cases, though, and this is one of them:
When copying an object, you want to get a resulting copy that matches exactly the state of the current self. The cleanest way of achieving this is often to set the copy's ivars explicitly, to prevent any side-effects that the init overloads or accessors might cause. It's "safe" because the code doing it is still located within the class that's in question, so if you needed to change or add ivars, you could update this code as well with the knowledge of anything else that might require.
Doing this from outside the class in question is bad form, and there's no good reason to do it.
In Objective-C you have some kind of two variable type accessors. The one everybody should know is the "." one (e.g. Class.variable). This type calls either the appropriate getter or setter.
Now, the other type - the one you asked for - is for in-class usage. Obviously, as the getter or setter gets called automatically with the "." notation you need a way to set the variable without a setter (calling the setter in the setter itself results in an endless loop). Therefore, this "->" notation is used -> simply, it is the direct-access mode.
Usually, Objective-C the variable name for both notations is the same but some prefer to have the in-class notation variable name beginning with "_". This is achieved by editing the #synthesize variable line to #synthesize variable = _variable.
That's a pointer indirection operator. a->b means the same thing as (*a).b (where the . is the structure member access operator, not Objective-C's property dot syntax).
When you say:
newItem->_stringValue
you're directly accessing the _stringValue instance variable of the object to which newItem points.
The -> operator is very common in C++, but not so much in Objective-C.
In Objective C, like in C++, the p->m notation is equivalent to (*p).m This is, the dereference of the pointer to the base type followed by a call to the corresponding method or property.
So in your case, using the other notation it would look like this:
(*newItem)._stringValue = [_stringValue copy];
(It's more common to use the -> operator)

method taking mutli arguments in dot notation

i am viewing this video on objective c. the guy show a method which takes multiple arguments and it looks like this
- (void) setTo: (int) n over: (int) d
{ .... }
to use it he shows:
[myFraction setTo: 100 over:200];
how would that bracket notation look in dot noation? andi dont understand what that over
means, would anyone know? thnx
The dot notation is a shorthand notation for property access only. The compiler translates it to the appropriate setter/getter method call. It is just syntactic sugar.
So given this property access using dot notation:
myFraction.numerator=100;
The compiler replaces it with the following equivalent code:
[myFraction setNumerator:100]
Now it should be clear why you cannot use dot notation for sending a normal message to an object. I can't even think of a way how that should even look like.
There is a lot of discussion concerning dot vs. bracket notation going on. One of the arguments against dot notation is the confusion it generates especially for beginners. Other languages do of course use methods for property accessors too, however they hide this fact more consistently than Objective-C.
You cannot pass multiple arguments with dot notations. A setter usable by dot-notation must have the prototype
-(void)setXxxx:(type)value;
However, you can create an auxiliary struct to group all arguments into one:
struct Fraction { int n, d; };
struct Fraction MakeFraction(int n, int d) {
struct Fraction r;
r.n = n;
r.d = d;
return r;
}
...
-(void)setValue:(struct Fraction)f { ... }
...
myFraction.value = MakeFraction(100, 200);
(and a "over" b means a / b.)
From the looks of it, this method is setting two instance variables/properties of the object the numerator (n) and the denominator (d). You cannot do this using dot notation unless you break it into two calls:
myFraction.numerator=100;
myFraction.denominator=200;
Note that dot notation is only for accessing instance variables/properties and not an alternative to message sending.
In Objective-C, we can name methods with arguments in the middle. So when he writes [myFraction setTo:100 over:200];, the over could mean... well, whatever he wants. It's part of the method name he chose. In this case, he was probably trying to make the method sound like English. ("Set this fraction to 100 over 200." We read fractions as "numerator over denominator" often in normal speech.)
Some methods, called "accessors", we write very frequently: these are methods of the form - (int)variable (called "getters"), and - (void)setVariable:(int)newValue (called "setters"). My examples here would assumedly return, or change, respectively, an instance variable called variable. Here's what the method implementations might look like:
- (int)variable
{
return variable;
}
- (void)setVariable:(int)newValue
{
variable = newValue;
}
It's common to have accessors like this for almost every instance variable your class has. At some point, someone got tired of writing [myInstance setVariable:20]; and such, and decided they'd rather it look like many other languages out there, myInstance.variable = 20;.
Therefore, Objective-C 2.0 added dot notation, which allows you to write...
myInstance.variable, which is exactly equivalent to [myInstance variable] in most circumstances (and does NOT access the instance variable variable directly!), and...
the special case myInstance.variable = 20;, which is exactly equivalent to [myInstance setVariable:20];. Again, note that this does not access variable directly, it sends a message to myInstance. So if we'd written some other code in setVariable, it would still be accessed if we used dot notation.
Dot notation is designed to be used for accessors. You could also theoretically use it for any method that returns a value and takes no arguments (myArray.count, for example). Using it for anything else (myInstance.doSomeAction) is extremely poor style. Don't do it. Therefore, as I'm sure you can guess by now, [myFraction setTo:100 over:200] has no dot notation equivalent, as it takes 2 arguments, and isn't an accessor.
[myFraction numerator]
Could be written as
myFraction.numerator
but you can also assign values such as
instance.property = value
But you cannot pass multiple arguments in dot notation.

self.variable and variable difference [duplicate]

This question already has answers here:
Difference between self.var and simply var
(3 answers)
Closed 8 years ago.
What is the difference between self.myVariable = obj; and myVariable = obj;, when I use #propery/#synthesize to create `myVariable?
It's important to note that dot-syntax is converted to a simple objc_msgSend call by the compiler: that is to say that underneath it acts exactly like a message send to the accessor for that variable. As such, all three of the following are equivalent:
self.myVariable = obj;
[self setMyVariable:obj];
objc_msgSend(self, #selector(setMyVariable:), obj);
Of course, this means that using dot-syntax actually results in a full message send, meaning calling a new function and all the overhead that is associated with it. In contrast, using simple assignment (myVariable = obj;) incurs none of this overhead, but of course it can only be used within the instance methods of the class in question.
The #synthesize directive tells the compiler to generate accessors for your member variables, according to the specifications given in the #property directive in your .h file. (I.e., if you specify retain, the setter will retain the variable, and if you specify copy, it will copy it.)
The accessors will (unless you specify otherwise) be named propertyName and setPropertyName.
Using the . notation (note, not the self syntax as stated above) is saying that you want to use the accessors (a good thing if you are setting strings, and want to ensure the retain count is correct, for example).
So, within your class implementation:
self.bill = fred will call the
accessor setBill.
bill = fred will set bill to fred
directly, without going through the
accessor.
One of the differences I found out when starting Cocoa development is if I set variable to use a #Property/#Synthesize syntax and I didn't use self.myVariable = obj or [self setMyVariable:obj] but instead myVariable = obj, the object is not retained if obj is released later. (Assuming #Property was set up to use retain.)
The reason is the retain count is not set when using myVariable = obj and when the obj is released the count is now zero. (Unless you retain it yourself) But by using the accessor it will do the retain count for you. (Again assuming you set it up to use retain when it was declared).
Shyne
If I can add one important note to this. The answer above are all awesome, so I won't add to the technical side. But just this:
If you create a synthesized property
#synthesize myProp;
Always use the self.myProp pattern to set it.
self.myProp = newVal;
This seems really obvious, but it's important. It's true that there is simply no reason to do this, but until you really understand how the synthesized setters are created you just want to assume you HAVE to use the self. pattern to set the value.
Honest: this will save you a lot of late night debug sessions. Non-retained memory access violations are simply the worst to debug.
The self syntax uses the accessor method, the other syntax does not. This might be a big difference if the accessor does something more than simply assign the new value. See the Declared Properties part of the Objective-C tutorial.
The other answers are correct, the difference is that the dot notation causes the ivar to be changed through the accessory rather than directly.
Until you know what you're doing, I recommend you use the dot notation (i.e. self.propertyName = ...). Cocoa/Obj-C does a lot with key-value coding, and while the phone SDK doesn't take full advantage of that (with things like bindings), eventually it will. Getting used to using the accessors now will save you a lot of headaches in the future.
Using the accessor methods also give you the opportunity to override them and provide more functionality should you need to. By simply changing the value of the ivar, you rob yourself of this capability.