【问题标题】:Creating a copy of an NSMutableArray with custom objects使用自定义对象创建 NSMutableArray 的副本
【发布时间】:2014-07-15 04:15:52
【问题描述】:

我一直在寻找解决这个问题的方法,但其他线程都没有帮助。基本上,我想要完成的是创建一个自定义对象数组作为单例,将它们加载到我的关卡中,然后创建它们的副本,因为分配给这些对象的变量将被操纵。但是,当关卡完成(或失败)时,我希望这些对象保持不变,以便重新加载它们。

以下是我尝试过的一些事情。

- (void)spawnStartTiles {
    //where _puzzleGridTilesArray and curLevel.gridTiles are NSMutableArrays
    [_puzzleGridTilesArray removeAllObjects];
    _puzzleGridTilesArray = [curLevel.gridTiles mutableCopy];
    CCLOG(@"tile in curlevel %@", curLevel.gridTiles[0]); //want these to log DIFFERENT objects
    CCLOG(@"tile in puzzle array %@", _puzzleGridTilesArray[0]);//want these to log DIFFERENT objects
}

以上记录了相同的对象 ID。

- (void)spawnStartTiles {
    //where _puzzleGridTilesArray and curLevel.gridTiles are NSMutableArrays
    _puzzleGridTilesArray = [self cloneArray:curLevel.gridTiles];
    CCLOG(@"tile in curlevel %@", curLevel.gridTiles[0]); //want these to log DIFFERENT objects
    CCLOG(@"tile in puzzle array %@", _puzzleGridTilesArray[0]);//want these to log DIFFERENT objects
}

-(NSMutableArray*)cloneArray:(NSMutableArray *)myArray {
    return [[NSMutableArray alloc] initWithArray: myArray];
}

仍然记录相同的对象 ID。

- (void)spawnStartTiles {
    //where _puzzleGridTilesArray and curLevel.gridTiles are NSMutableArrays
    _puzzleGridTilesArray = [[NSMutableArray alloc] initWithArray:curLevel.gridTiles copyItems:YES];
    CCLOG(@"tile in curlevel %@", curLevel.gridTiles[0]); //want these to log DIFFERENT objects
    CCLOG(@"tile in puzzle array %@", _puzzleGridTilesArray[0]);//want these to log DIFFERENT objects
}

上面给出了一个运行时错误。我认为这是因为我正在复制的对象是一个名为 Tile 的自定义类。该类是一个CCNode,.h文件在下面。

#import "CCNode.h"

@interface Tile : CCNode

@property (nonatomic, assign) NSInteger value;
@property (nonatomic, assign) NSInteger gemLevel;
@property (nonatomic, assign) BOOL mergedThisRound;
- (void)updateValueDisplay:(BOOL)bannerTiles difficultyMode:(int)difficultyMode;
- (void)updateOpacity:(NSInteger)opacityVariable;
- (void)tileHasBeenSelected:(BOOL)tileHasBeenTouched;

@end

有没有办法以某种方式转换这个类以便可以复制它?我查看了http://www.techotopia.com/index.php/Copying_Objects_in_Objective-CImplementing NSCopying 仍然感到困惑,因此将不胜感激进一步的帮助。谢谢!

【问题讨论】:

    标签: objective-c cocos2d-iphone


    【解决方案1】:

    您收到错误,因为[[NSMutableArray alloc] initWithArray:curLevel.gridTiles copyItems:YES] 对数组中的每个项目调用copyWithZone:。您的商品必须符合NSCopying 才能使用此方法,但这是正确的方法。

    实现 NSCopying:

    1. 更新您的Tile 类以添加协议,即@interface Tile : CCNode <NSCopying>
    2. 在您的 Tile 实现中实现方法 - (id)copyWithZone:(NSZone *)zone
    3. 在该方法中,分配Tile 的新实例并将其所有属性分配给当前实例的属性。

    【讨论】:

    • 谢谢!这对我有用 =) 现在我也更好地理解它了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2016-08-08
    • 2011-01-28
    相关资源
    最近更新 更多