将对象从一个NSMutableArray复制到另一个NSMutableArray(copy objects from one NSMutableArray to another NSMutableArray)

我试图理解从一个NSMutableArray复制对象到另一个NSMutableArray。 请考虑以下两种情况:1 - 将原始文件复制到克隆,其中克隆中的更改将影响原始文件。 2 - 将原件复制到克隆,其中关闭的更改不会影响原件。

首先,我尝试使用以下代码首先生成场景#1。 根据我的理解,当复制数组不使用'mutablecopy'时,克隆数组将只保存指向原始字符串对象的指针。 所以,如果我要将克隆的第一个元素更改为另一个对象,原始的第一个元素会改变得太对吗? ......但这不是我得到的结果。 为什么?

事实上,当我使用mutablecopy时

[self.cloneArray addObject:[[self.originalArray objectAtIndex:i] mutableCopy]];

我得到了相同的结果。 我很困惑。

ArrayClass.h

@interface ArrayClass : NSObject {
    NSMutableArray *_originalArray;
    NSMutableArray *_cloneArray;
}

@property (nonatomic, retain) NSMutableArray *originalArray;
@property (nonatomic, retain) NSMutableArray *cloneArray;

ArrayClass.m

@synthesize originalArray = _originalArray;
@synthesize cloneArray = _cloneArray;

_originalArray = [[NSMutableArray alloc] initWithObjects: @"one", @"two", @"three", @"four", @"five", nil];
_cloneArray = [[NSMutableArray alloc] initWithCapacity:[self.originalArray count]];

for (int i=0; i<5; i++) {
    [self.cloneArray addObject:[self.originalArray objectAtIndex:i]];
}

// make change to the first element of the clone array
[self.cloneArray replaceObjectAtIndex:0 withObject:@"blah"];

for (int n=0; n<5; n++) {
    NSLog(@"Original:%@ --- Clone:%@", [self.originalArray objectAtIndex:n], [self.cloneArray objectAtIndex:n]);
}

...

2011-03-27 03:23:16.637 StringTest[1751:207] Original:one --- Clone:blah
2011-03-27 03:23:16.638 StringTest[1751:207] Original:two --- Clone:two
2011-03-27 03:23:16.639 StringTest[1751:207] Original:three --- Clone:three
2011-03-27 03:23:16.642 StringTest[1751:207] Original:four --- Clone:four
2011-03-27 03:23:16.643 StringTest[1751:207] Original:five --- Clone:five

I am trying to understand copying objects from one NSMutableArray to another. Consider the following 2 scenarios: 1 - copying original to clone where changes in the clone will affect the original. 2 - copying original to clone where the changes in the close will NOT affect the original.

First, I am trying to produce scenario #1 first with the following code. From what I understand, when copying array not using 'mutablecopy', the clone array will just hold the pointer to the same string objects in the original. So if I were to change the first element of the clone to a different object, the first element of the original would change too right? ... but that's not the result I am getting. Why?

Matter of fact, when I use mutablecopy

[self.cloneArray addObject:[[self.originalArray objectAtIndex:i] mutableCopy]];

I get the same result. I am confused.

ArrayClass.h

@interface ArrayClass : NSObject {
    NSMutableArray *_originalArray;
    NSMutableArray *_cloneArray;
}

@property (nonatomic, retain) NSMutableArray *originalArray;
@property (nonatomic, retain) NSMutableArray *cloneArray;

ArrayClass.m

@synthesize originalArray = _originalArray;
@synthesize cloneArray = _cloneArray;

_originalArray = [[NSMutableArray alloc] initWithObjects: @"one", @"two", @"three", @"four", @"five", nil];
_cloneArray = [[NSMutableArray alloc] initWithCapacity:[self.originalArray count]];

for (int i=0; i<5; i++) {
    [self.cloneArray addObject:[self.originalArray objectAtIndex:i]];
}

// make change to the first element of the clone array
[self.cloneArray replaceObjectAtIndex:0 withObject:@"blah"];

for (int n=0; n<5; n++) {
    NSLog(@"Original:%@ --- Clone:%@", [self.originalArray objectAtIndex:n], [self.cloneArray objectAtIndex:n]);
}

...

2011-03-27 03:23:16.637 StringTest[1751:207] Original:one --- Clone:blah
2011-03-27 03:23:16.638 StringTest[1751:207] Original:two --- Clone:two
2011-03-27 03:23:16.639 StringTest[1751:207] Original:three --- Clone:three
2011-03-27 03:23:16.642 StringTest[1751:207] Original:four --- Clone:four
2011-03-27 03:23:16.643 StringTest[1751:207] Original:five --- Clone:five

原文:https://stackoverflow.com/questions/5447853
2022-11-29 22:11

满意答案

默认情况下, object prototype是一个空对象。

classA.prototype = { x: 4, y: 6 };
classA.prototype.prototype = { z: 10 };

相当于

classA.prototype = { x: 4, y: 6, prototype: { z: 10 }};

您只需将名为prototype的属性添加到classA

z是属于classA的对象prototype的属性

alert(foo.prototype.z); 将工作


By default an object prototype is an empty object.

classA.prototype = { x: 4, y: 6 };
classA.prototype.prototype = { z: 10 };

is equivalent to

classA.prototype = { x: 4, y: 6, prototype: { z: 10 }};

you just added a property named prototype to classA

z is a property of the object prototype belonging to classA

alert(foo.prototype.z); will work

相关问答

更多

JavaScript初学者:为什么这不起作用?(JavaScript beginner: why does this not work?)

很少有误解: checkAvailability是一个函数,你缺少parens。 访问getHotelName函数时,您必须引用HiltonHotel变量,才能访问和调用该函数。 您的html代码中的一些小错误,在代码段中运行时,您不必添加单独的脚本,默认情况下它连接在一起。 var firstName = 'Steven'; var lastName = 'Curry'; var fullName = firstName + ' ' + lastName; function Hotel...

javascript原型:为什么这不起作用?(javascript prototyping: why doesn't this work?)

默认情况下, object prototype是一个空对象。 classA.prototype = { x: 4, y: 6 }; classA.prototype.prototype = { z: 10 }; 相当于 classA.prototype = { x: 4, y: 6, prototype: { z: 10 }}; 您只需将名为prototype的属性添加到classA z是属于classA的对象prototype的属性 alert(foo.prototype.z); 将工作 B...

Javascript中基本原型的问题(Problems with basic prototyping in Javascript)

您不分配Obj对象的属性,但在构造函数中只有一个局部变量。 像这样改变: function Obj(n){ this.name = n; } 示例小提琴 You not assigning a property of the Obj object, but just have a local variable inside the constructor. Change like this: function Obj(n){ this.name = n; } Example F...

Javascript OOP - 继承和原型设计(Javascript OOP - inheritance and prototyping)

尝试这个: function Car () { this.totalDistance = 0; }; Car.prototype.putTotalDistance = function(distance) { this.totalDistance = distance; }; Car.prototype.getTotalDistance = function() { return this.totalDistance; }; Car.proto...

为什么这不起作用?(Why doesn't this work?)

您只分配一次数据 - 但GLUtesselator一次只需要一组数据! 你在这里做的是将所有顶点数据放在内存中的一个位置,在原始代码中,每个顶点都有内存。 GLUtesselator需要多个顶点才能正常运行。 你打电话 void gluDeleteTess(GLUtesselator *tessobj); ......之后,你呢? You allocate the data only once -- but GLUtesselator needs more than one set of dat...

使用Javascript进行原型设计(Prototyping in Javascript)

ECMAScript(JavaScript)支持“基于原型的继承”。 这意味着JS中的“class”和“instance”没有区别。 反对其他语言的OOP,在JS中,“类”和“实例”基本上是相同的东西: 当你定义“Bla”时,它会立即立即(准备使用),但也可以作为“原型”来克隆具有相同属性和方法的另一个实例的对象“Bla”的初始定义(!)。 在其他OOP语言中,您有定义部分的“类”。 prototype对象适用于在初始定义之后扩展“Bla”原型(请参阅:class“Bla”)并将新属性/函数添加到...

JavaScript / jQuery为什么这不起作用?(JavaScript / jQuery why doesn't this work?)

如果您更符合逻辑地格式化您的代码,则会更清楚您的意图。 在$ .post()调用中,关闭函数上的大括号,但不要关闭$ .post()paren。 更换: $.post(postFilen, function(data){ $("#msg").html(data).find("#message2").fadeIn("slow") } 有: $.post(postFilen, function(data){ $("#msg").html(data).find("#message2")...

Javascript:使用性能参数对函数进行原型设计(Javascript: Prototyping a function with arguments for performance)

是的,这就是“所有原型”的缺点 - 你不能访问构造函数参数 - 它们只能在函数体内部使用(例如,你将它们放在那里的公共属性中)。 需要使用它们的所有东西都不属于原型; 您只会在原型上填充“默认属性”(通常是所有实例共有的方法)。 我想你不管怎么说都不需要。 该模式仅对真正的构造函数有用,你似乎没有这里(我会期待this.Subscription )。 此外,承诺的“性能提升”可以忽略不计。 如果你真的想在这里使用它,它将是: function Class() { this.Subscript...

为什么这不起作用?(Why doesn't this work? sqlit3 php)

我不认为你可以使用绑定列名称。 我建议动态创建SQL语句,但只有在验证了$ by参数与现有列名匹配后(避免SQL注入的风险): $numFields = array("user_id", "phone", "fax", "zip", "admin"); $charFields = array("email"); $allFields = array_merge($numFields, $charFields); $row = array(); if (isset($by) && isset($v...

Javascript中的单例和原型(Singleton and Prototyping in Javascript)

建议的解决方案似乎并没有“解决”任何问题1 ; 因此,我推荐使用惯用IIFE的“简单模块模式”的标准变体: MySingleton = (function () { // This function is only executed once // and whatever is returned is the singleton. return { // Expose members here }; })(); 根据具体需要,还可以返回一个新的对象...

相关文章

更多

Guava Objects类详解

Objects.toStringHelper(s1)

微信,从一个QQ到另一个QQ

微信。就是从一个QQ到另一个QQ,褪去QQ不成熟的外衣。穿上一件假装成熟的外套。 以腾讯的能力。绝对可 ...

将某个条目复制到其他分组的方案

现在想大概实现这样的功能,长按某个条目后在弹出的context menu上有一个选项,然后可以将该条目 ...

Hadoop 本地文件复制到hdfs目录

Hadoop 本地文件复制到hdfs目录 publicstaticvoidmain(Strin ...

关于对象复制时出现内容不一致的问题

Object.extend=function(a,b){ for(k in b){ alert(k ...

原创:用VBA实现将鼠标选择的单元格按照指定格式合并并复制到剪切板

原创:用VBA实现将鼠标选择的单元格按照指定格式合并并复制到剪切板 一、主要实现以下功能: 1、用鼠标 ...

数据复制问题

有一个线上的数据库,知道线上某一个用户的user_id,要把跟他有关的的所有数据,复制到本地的测试数据 ...

快速了解mybatis

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避 ...

对象关系映射(ORM)-Oceanus编码调用

Oceanus定位于分布式存储数据的中间件解决方案,分布式环境中对数据存储的结构和读写方式都有较高的要 ...

一段代码的疑问

Function.prototype.method = function(name, func) { ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本