objective-c - 复制自定义对象

标签 objective-c ios

我有一个名为 Layer 的对象,它有一些属性和一些方法。

我需要将图层传递给第二个 View Controller :

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];

在 SecondVC 中,我可能会更改属性。然后我通过委托(delegate)返回 Layer 对象;
-(void)done
{
    [self.delegate returnLayer:self.layer];

    [self dismissModalViewControllerAnimated:YES];
}

现在我的问题是我正在传递一个指向我的第一个 View Controller 的图层对象的指针,当我在第二个 View Controller 中更新图层时,我的第一个 View Controller 的图层对象也正在更新。

因此,我无法判断它是否已更改(如果已更改,我需要运行一些代码)。

如何创建我的图层对象的副本并将其传递给我的第一个 View Controller 的图层对象而不是指针?

编辑:

我确实尝试使用第二种初始化方法:
-(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;
}

没有成功。

编辑2:

试过了
Layer *copyLayer = [self.myLayer copy];

layerView.myLayer = copyLayer;

并得到错误
-[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'

解决了:

我在 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]];
}

这给了我一个图层对象的副本

最佳答案

您将需要实现 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;
}

现在在你的调用函数中
//instead of passing self.Layer pass [self.Layer copy]
view.Layer = [[Layer alloc] initWithMapLayer:[self.Layer copy]];

关于objective-c - 复制自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11000192/

相关文章:

iphone - 一个有 2 个所有者的对象

c# - Xcode Cocoa - 从 NSTableView 拖放到 Finder

ios - 在 UIWebView 中获取页面标题?

ios - 格式字符串未使用数据参数

ios - NSString 在出现的字符串周围添加标签

objective-c - 如何在 Interface Builder 中更改 UIButton 的背景图像并保留其形状?

iphone - _myObject 与 self.myObject

iOS : display the array value in uitextfield?

ios - Xcode 6 进程启动失败 : timed out trying to launch app

ios - 将 GPUImage 滤镜应用于部分视频