使用指针将数组元素复制到其他数组

时间:2012-02-19 21:59:27

标签: objective-c nsmutablearray

假设我有NSMutableArray *array1个10个对象。我想创建一个*array2并添加从array1array2的5个对象,我想要它,以便当我从array2更改这些对象属性时,它们也会更改来自array1的5个特定对象。我该怎么做?

编辑:好的我想我问的是错误的问题。它更多的是通过引用和指针传递,我太过分了:

NSMutableArray *mainArray;
NSMutableArray *secondaryArray;
NSMutableDictionary *dic1;

[mainArray addObject:dic1];
[self changeValues:[mainArray lastObject]];

-(void)changeValues:(NSMutableDictionary*)someDic
{
    [secondaryArray addObject:someDic];
    NSMutableDictionary *aDic=[secondaryArray lastObject];
    ...//some code to change values of aDic
    //by changing aDic, I want to also change the same dic from mainArray

    //so [mainArray lastObject] should be the same exact thing as [secondaryArray lastObject]
}

如何更改上述代码,以便更改反映在两个数组中?

2 个答案:

答案 0 :(得分:1)

NSMutableArray *array2 = [NSMutableArray array];
for (int i=0; i<5; ++i){
    [array2 addObject: [array1 objectAtIndex:i] ]
}

在此示例中,您具有由array1项和项目指向的对象集 array2,因为NSMutableArray包含指向对象的指针,而不包含自己的对象。 因此,通过一个数组中的指针更改对象,您可能会观察到通过更改 来自其他数组的指针。


修改

@mohabitar,你已经收到了答案。 dic1someDicaDic - 所有这些值都相同。只需更改aDic(或someDic)并查看结果。

答案 1 :(得分:0)

这听起来像某些KVC(键值编码)的好例子。

使用KVC,您可以创建索引属性,并让KVC引擎为索引属性创建一个数组代理,然后允许您对索引属性进行操作,就像它是一个数组一样。

以下是在OS X和iOS上都经过测试的快速概念验证代码。

接口:

@property (strong) NSMutableArray *mainArray;

实现:

@synthesize mainArray   = _mainArray;


- (id)init
{
    self = [super init];
    if (self) {

        // For simplicity, use strings as the example
        _mainArray = [NSMutableArray arrayWithObjects:
                      @"1st element",
                      @"2nd element",
                      @"3rd element",
                      @"4th element",
                      @"5th element",
                      @"6th element",
                      @"7th element",
                      @"8th element",
                      @"9th element",
                      @"10th element",
                      nil];
    }
    return self;
}


// KVC for a synthetic array, accessible as property @"secondaryArray"

- (NSUInteger) countOfSecondaryArray
{
    return 5;
}


- (id) objectInSecondaryArrayAtIndex: (NSUInteger) index
{
    // In practice you would need your mapping code here. For now
    // we just map through a plain C array:

    static NSUInteger mainToSecondaryMap[5] = {1,4,5,7,8};

    return [self.mainArray objectAtIndex:mainToSecondaryMap[index]];
}


- (void) watchItWork
{
    NSArray *secondaryArray = [self valueForKey:@"secondaryArray"];

    // See how the sub array contains the elements from the main array:

    NSLog(@"%@", secondaryArray);

    // Now change the main array and watch the change reflect in the sub array:

    [self.mainArray replaceObjectAtIndex:4 withObject:@"New String"];

    NSLog(@"%@", secondaryArray);
}

docs中有更多信息,特别是关于索引访问者模式的部分。