NSArray和NSString [英] NSArray and NSString

查看:98
本文介绍了NSArray和NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读的书让我写了以下代码:

The book I'm currently reading has me write the following code :

-(IBAction)displaySomeText:(id)sender {
    NSString *cow = @"Milk";
    NSString *chicken = @"Egg";
    NSString *goat = @"Butter";

    NSArray *food = [NSArray arrayWithObjects:cow, chicken, goat, nil];

    NSString *string = @"The shopping list is: ";
    string = [string stringByAppendingString:[food componentsJoinedByString:@", "]];

    [textView insertText:string];

}

我对数组的工作原理有所了解,但是我需要帮助来了解以下代码

I understand somewhat how arrays work but I need help understanding the following code

string = [string stringByAppendingString:[food componentsJoinedByString:@", "]];

我从未见过这样的情况.

I have never ever seen an instance where this is possible.

他让我从NSString类创建一个字符串"对象,然后我就这样做了

He has me create a 'string' object, from the NSString class, and then I'm doing this

string = [string stringByAppendingString:];

我很困惑.我从未见过创建对象然后在相同对象上执行方法并将其存储在完全相同的对象中的示例.

I'm confused. I have never seen an example where I create an object and then perform a method on the same object and store it in that exact same object.

例如,我知道我可以做到

For example, I know I can do this

NSSound *chirp;
chirp = [NSSound soundNamed:@"birdChirp.mp3"];

上面的解释很有意义,因为我使用了创建的对象并对其执行了类方法.

the above makes sense because I used the created object and performed a class method on it..

但是我一直以为以下代码不可能等效

but I always assumed that the equivalent of the following code was NOT possible

chirp = [chirp methodNameEtc..];

我希望我能很好地解释我的问题.如果没有,我总是可以进一步阐述.

I hope I explained my question well. If not I could always elaborate further.

推荐答案

我认为这是您问题的核心我很困惑.我从未见过创建对象然后执行操作的示例.方法在同一个对象上并将其存储在该完全相同的对象中."

I think this is the heart of your question "I'm confused. I have never seen an example where I create an object and then perform a method on the same object and store it in that exact same object."

要回答该问题,您实际上不是"将其存储在完全相同的对象中".您正在做的是混淆pointersobjects.

To answer that question, your not actually 'storing it in the exact same object'. What you are doing is confusing pointers and objects.

让我们看看这一行:

string = [string stringByAppendingString:@"Hello"];

在这一行中,字符串"是一个pointer,而不是它指向的object.此行代码所说的是: 当前由pointer'字符串'引用的Object,返回给我一个新的NSString object,其文本是添加了该文本的您的文本.当我得到新的NSString object时,我订购了使pointer'字符串'指向该object."

In this line 'string' is a pointer, not the object it points to. What this line of code is saying is: "Object currently referenced by the pointer 'string', return to me a new NSString object whose text is your text with this text added. And when I get that new NSString object I ordered make the pointer 'string' point to that object instead."

这篇关于NSArray和NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆