简体   繁体   English

Objective C方法和语法

[英]Objective C Methods and syntax

I am a bit confused when working with objective-c. 使用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.. 到目前为止,我一直学习Objective-C,我一直认为自己可以做这样的事情。

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? 两者有什么区别?

The first one ( object = [object method]; ) is an assignment of whatever method returns. 第一个( object = [object method]; )是对任何方法返回的赋值。

The second one ( [object method]; ) is just calling the method without paying attention to its return value (if any). 第二个[object method];[object method]; )只是调用该方法而没有注意其返回值(如果有)。

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. 第三个( NSString *object = [[NSString alloc]initWithFormat:@"@"] )声明变量,并分配在alloc类方法的返回值上调用的initWithFormat方法的返回值。

In many programming languages, object = [object method]; 在许多编程语言中, 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. 计算变量y和z的总和,然后将其存储在名为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". 告诉名为“ object”的对象执行“方法”,并将结果存储回“ 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]; 您的示例object = [object method]; is simply a more complex version of that. 只是一个更复杂的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM