完全困惑在这里。NSArray/NSMutableArray:通过ref或通过值?
我有一个PARENT UIViewController需要传递一个NSMutableArray到一个CHILD UIViewController。我期待它通过引用传递,这样CHILD中所做的更改将反映在PARENT中,反之亦然。但事实并非如此。两者都有一个财产宣布为..
@property (nonatomic, retain) NSMutableArray *photos
;
例子:
父:
self.photos = [[NSMutableArray alloc] init];
ChildViewController *c = [[ChildViewController alloc] init ...];
c.photos = self.photos;
...
...
...
儿童:
[self.photos addObject:obj1];
[self.photos addObject:obj2];
NSLog(@"Count:%d", [self.photos count]) // Equals 2 as expected
...
返回父:
NSLog(@"Count:%d", [self.photos count]) // Equals 0 ... NOT EXPECTED
我以为他们都会访问相同的内存。这不是这种情况吗?如果它不是...我如何保持两个NSMutableArrays同步?
更新与更多的代码...
在父母的UIViewController:
- (void)loadView {
self.photos = [[NSMutableArray alloc] init];
// Create view for root controller
UIView *rootView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
self.view = rootView;
self.view.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"green_felt_bg.jpg"]];
[rootView release];
ChildViewController *c = [[ChildViewController alloc] initWithNibName:@"ChildView" bundle:nil];
self.childViewController = c;
[c release];
self.childViewController.photos = self.photos;
self.childViewController.delegate = self;
[self.view insertSubview:self.childViewController.view atIndex:0];
}
在孩子的ViewController我只是将对象添加进去。在完成添加PARENT处理的对象时调用委托方法。没有其他重要的事情发生。代码孩子使用修改它的“照片”属性..
[[self mutableArrayValueForKey:@"photos"]
addObject:[photo resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(200.0f, 300.0f) interpolationQuality:kCGInterpolationLow]];
你的直觉是正确的;如果两个属性确实是'retain'(而不是'copy'!),那么最后一个'NSLog'应该是2.看起来你需要发布更多的代码。父母的照片属性有可能在某个时候被修改过吗? – andyvn22 2010-04-16 01:47:45
是的..这两个属性都是保留...并且不行,父母的照片属性没有被修改。如果我回到孩子控制器,计数仍然是“2”。这让我疯狂 – wgpubs 2010-04-16 02:06:02
尝试发布孩子的'addObject:'行被取出的确切方法,以及在'c.photos = self.photos;'和'NSLog'之间的父代码... – andyvn22 2010-04-16 02:09:29