假设我有10个对象的NSMutableArray *array1。我希望创建一个*array2,并将5个对象从array1添加到array2,因此当我从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]
}我将如何更改上述代码,以使更改反映在两个数组中?
发布于 2012-02-19 22:07:15
NSMutableArray *array2 = [NSMutableArray array];
for (int i=0; i<5; ++i){
[array2 addObject: [array1 objectAtIndex:i] ]
}在本例中,您有一组由array1项和array2项指向的对象,因为NSMutableArray包含指向对象的指针,而不是它们自己的对象。因此,在一个数组中更改对象that指针,您可能会观察到从其他数组中更改了that指针。
编辑
@mohabitar,你已经收到了答案。dic1、someDic和aDic --所有这些值都是相同的。只需更改aDic(或someDic)并查看结果。
发布于 2012-02-20 11:09:46
对于某些KVC (键值编码)来说,这似乎是一个很好的例子。
使用KVC,您可以创建索引属性,并让KVC引擎为索引属性创建数组代理,然后允许您像对数组一样对索引属性进行操作。
下面是在OS和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);
}文档中有更多的信息,特别是索引访问器模式的部分。
https://stackoverflow.com/questions/9353675
复制相似问题