我有一个名为Layer的对象,它有一些属性和一些方法.
我需要将Layer传递给第二个视图控制器:
SecondVC *view = [self.storyboard instantiateViewControllerWithIdentifier:@"2VC"];
view.Layer = [[Layer alloc] initWithMapLayer:self.Layer];
view.delegate = self;
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:view];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:navController animated:YES];
Run Code Online (Sandbox Code Playgroud)
在SecondVC中,我可能会更改属性.然后我通过委托返回Layer对象;
-(void)done
{
[self.delegate returnLayer:self.layer];
[self dismissModalViewControllerAnimated:YES];
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是我将指针传递给我的第一个视图控制器的Layer对象,当我更新第二个视图控制器中的Layer时,我的第一个视图控制器的Layer对象也正在更新.
因为这个,我无法判断它是否已被更改(如果有,我需要运行一些代码).
我如何创建我的Layer对象的副本并将其传递给我的第一个视图控制器的Layer对象而不是指针?
编辑:
我尝试使用第二个init方法:
-(id)initWithLayer:(Layer *)Layer
{
if (self = [super init])
{
self.call = [[FunctionCall alloc] init];
self.HUD = [[MBProgressHUD alloc] init];
self.Layers = [[NSMutableDictionary dictionaryWithDictionary:Layer.Layers] copy];
self.nameList = [[NSArray arrayWithArray:Layer.nameList] copy];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
没有成功.
EDIT2:
试着
Layer *copyLayer = [self.myLayer copy];
layerView.myLayer = copyLayer;
Run Code Online (Sandbox Code Playgroud)
并得到错误
-[layer copyWithZone:]: unrecognized selector sent to instance 0xfc72c40
2012-06-12 11:15:28.584 Landscout[8866:1fb07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Layer copyWithZone:]: unrecognized selector sent to instance 0xfc72c40'
Run Code Online (Sandbox Code Playgroud)
解决了:
我在initWithLayer方法中添加了一个深层副本:
for (id key in layer.layers)
{
[newLayers setValue:[[layer.layers objectForKey:key] mutableCopy] forKey:[key mutableCopy]];
}
for (id name in layer.nameList)
{
[newList addObject:[name mutableCopy]];
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个Layer对象的副本
您需要为copy对象实现函数
在你的Layer.m中
- (id)copy
{
Layer *layerCopy = [[Layer alloc] init];
//YOu may need to copy these values too, this is a shallow copy
//If YourValues and someOtherValue are only primitives then this would be ok
//If they are objects you will need to implement copy to these objects too
layerCopy.YourValues = self.YourValues;
layerCopy.someOtherValue = self.someOtherValue;
return layerCopy;
}
Run Code Online (Sandbox Code Playgroud)
现在在你的通话功能
//instead of passing self.Layer pass [self.Layer copy]
view.Layer = [[Layer alloc] initWithMapLayer:[self.Layer copy]];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4720 次 |
| 最近记录: |