首页 \ 问答 \ 将对象从一个NSMutableArray复制到另一个NSMutableArray(copy objects from one NSMutableArray to another NSMutableArray)

将对象从一个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

相关问答

更多
  • 很少有误解: checkAvailability是一个函数,你缺少parens。 访问getHotelName函数时,您必须引用HiltonHotel变量,才能访问和调用该函数。 您的html代码中的一些小错误,在代码段中运行时,您不必添加单独的脚本,默认情况下它连接在一起。 var firstName = 'Steven'; var lastName = 'Curry'; var fullName = firstName + ' ' + lastName; function Hotel(Hote ...
  • 默认情况下, 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 def ...
  • 您不分配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 Fiddle ...
  • 尝试这个: function Car () { this.totalDistance = 0; }; Car.prototype.putTotalDistance = function(distance) { this.totalDistance = distance; }; Car.prototype.getTotalDistance = function() { return this.totalDistance; }; Car.prototype. ...
  • 您只分配一次数据 - 但GLUtesselator一次只需要一组数据! 你在这里做的是将所有顶点数据放在内存中的一个位置,在原始代码中,每个顶点都有内存。 GLUtesselator需要多个顶点才能正常运行。 你打电话 void gluDeleteTess(GLUtesselator *tessobj); ......之后,你呢? You allocate the data only once -- but GLUtesselator needs more than one set of data at ...
  • ECMAScript(JavaScript)支持“基于原型的继承”。 这意味着JS中的“class”和“instance”没有区别。 反对其他语言的OOP,在JS中,“类”和“实例”基本上是相同的东西: 当你定义“Bla”时,它会立即立即(准备使用),但也可以作为“原型”来克隆具有相同属性和方法的另一个实例的对象“Bla”的初始定义(!)。 在其他OOP语言中,您有定义部分的“类”。 prototype对象适用于在初始定义之后扩展“Bla”原型(请参阅:class“Bla”)并将新属性/函数添加到所有当前和 ...
  • 如果您更符合逻辑地格式化您的代码,则会更清楚您的意图。 在$ .post()调用中,关闭函数上的大括号,但不要关闭$ .post()paren。 更换: $.post(postFilen, function(data){ $("#msg").html(data).find("#message2").fadeIn("slow") } 有: $.post(postFilen, function(data){ $("#msg").html(data).find("#message2").fade ...
  • 是的,这就是“所有原型”的缺点 - 你不能访问构造函数参数 - 它们只能在函数体内部使用(例如,你将它们放在那里的公共属性中)。 需要使用它们的所有东西都不属于原型; 您只会在原型上填充“默认属性”(通常是所有实例共有的方法)。 我想你不管怎么说都不需要。 该模式仅对真正的构造函数有用,你似乎没有这里(我会期待this.Subscription )。 此外,承诺的“性能提升”可以忽略不计。 如果你真的想在这里使用它,它将是: function Class() { this.Subscription = ...
  • 我不认为你可以使用绑定列名称。 我建议动态创建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($value) ...
  • 建议的解决方案似乎并没有“解决”任何问题1 ; 因此,我推荐使用惯用IIFE的“简单模块模式”的标准变体: MySingleton = (function () { // This function is only executed once // and whatever is returned is the singleton. return { // Expose members here }; })(); 根据具体需要,还可以返回一个新的对象,使这种模 ...

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)