问题
I am a bit confused when working with objective-c. This part in particular confuses me a lot.
What is the purpose and/ or difference between writing code like this ...
object = [object method];
and
[object method];
Learning objective-c up until now, I always assumed that I could do something like this..
say I had already created this..
NSString *object = [[NSString alloc]initWithFormat:@"%@"];
then I could do what I want with that like so..
[object applyAnyMethodHere];
but now I'm seeing things like this ..
object = [object applyAnyMethodHere];
What is the difference between these two?
回答1:
The first one (object = [object method];) is an assignment of whatever method returns.
The second one ([object method];) is just calling the method without paying attention to its return value (if any).
The third (NSString *object = [[NSString alloc]initWithFormat:@"@"]) declares variable and assigns the return value of the initWithFormat method called on the return value of the alloc class method.
回答2:
In many programming languages, object = [object method]; is what is called an "assignment" statement. Consider:
x = y + z;
The statement is read by the computer from right to left to mean:
Calculate the sum of the variables y and z and then store it in the variable called x.
The contents of the right side of your expression don't matter so much as what is actually happening in the whole statement. In your example, the computer will:
Tell an object named "object" to perform "method" and store the results back in "object".
However, you don't always want to store the results of a method call. For example, if you want to present an alert view, you may simply call:
[myalertView show];
Notice that there is no assignment happening. Assignment is not required, unless you want to store the value returned by a method call.
Also, consider this:
NSInteger x = 5;
There is no method call, but there is an assignment. Your example of object = [object method]; is simply a more complex version of that.
来源:https://stackoverflow.com/questions/8375179/objective-c-methods-and-syntax