0

我想知道如何通过向函数提供输入参数来检索值。我想在下面以这种方式检索,但它不会检索它,而是在打印时给出空数组值。我什至不能在参数中使用像 c 这样的 & 符号。

NSMutableArray *firstArray = [[NSMutableArray alloc] init];
NSMutableArray *secondArray = [[NSMutableArray alloc] init];

MyClass *myClassObj = [[MyClass alloc] init];
[myClassObj getVals : firstArray : secondArray];
NSLog(@"firstArray: %@", firstArray); // empty
            NSLog(@"secondArray: %@", secondArray); // empty

    // function to retrieve 
    - (void) getVals :(NSMutableArray *) firstArray :(NSMutableArray *) secondArray
    {
        firstArray = [NSMutableArray arrayWithObjects:@"val1", @"val2", @"val3", @"val4", nil];
        secondArray = [NSMutableArray arrayWithObjects:@"val11", @"val22", @"val33", @"val44", nil];


    }
4

2 回答 2

1

Try this:

- (void) getVals :(NSMutableArray *) firstArray :(NSMutableArray *) secondArray {
    [firstArray addObjectsFromArray:@[ @"val1", @"val2", @"val3", @"val4" ]];
    [secondArray addObjectsFromArray:@[ @"val11", @"val22", @"val33", @"val44" ]];
}

The code you have assigns a new array to the local parameter values instead of adding values to the passed in arrays.

Your other option could be:

NSMutableArray *firstArray = nil;
NSMutableArray *secondArray = nil;

MyClass *myClassObj = [[MyClass alloc] init];
[myClassObj getVals : &firstArray : &secondArray];

- (void) getVals :(NSMutableArray **) firstArray :(NSMutableArray **) secondArray {
    *firstArray = [NSMutableArray arrayWithObjects:@"val1", @"val2", @"val3", @"val4", nil];
    *secondArray = [NSMutableArray arrayWithObjects:@"val11", @"val22", @"val33", @"val44", nil];
}
于 2013-01-07T14:54:19.380 回答
0

您正在用新对象覆盖对象引用。你应该使用

[firstArray addObject:@"val1"]
于 2013-01-07T14:51:31.490 回答