【发布时间】:2013-07-29 06:52:18
【问题描述】:
我正在 Xcode 4.6.1 上为 iOS 6 开发
我正面临一个非常奇怪的问题。当您将NSMutableArrays 分配给另一个NSMutableArray 时,它们是否会以某种方式“链接”?
这是我的代码:
ViewController.m
@interface ViewController ()
{
NSMutableArray *one;
NSMutableArray *two;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
one = [[NSMutableArray alloc] init];
two = [[NSMutableArray alloc] init];
[one addObject:@"item1"];
[one addObject:@"item2"];
[one addObject:@"item3"];
two = one;
NSLog(@"First log: %@ and %@",one, two);
[one addObject:@"item4"];
NSLog(@"Second log: %@ and %@",one, two);
}
我只是在one 中添加了 3 个项目。然后我将它分配给two。现在,当我将另一个对象添加到 one 时,它也会添加到 two 中。为什么是这样?它们是否以某种方式“联系”起来?
这是日志:
First log: (
item1,
item2,
item3
) and (
item1,
item2,
item3
)
Second log: (
item1,
item2,
item3,
item4
) and (
item1,
item2,
item3,
item4
)
我的解决方法是使用NSArray 而不是NSMutableArray,因为NSArrays 不可更改。但我真的很想知道为什么会这样?我是否遗漏了一些非常明显的东西?
谢谢!
【问题讨论】:
-
这是完全正常的。
标签: objective-c ios6 nsmutablearray nsarray xcode4.6