我正在使用 Objective-C 开发 iPhone 应用程序。我有 A 类,它创建了一个名为“list”的 NSMutableArray 指针。但是,在 A 类中,我从来没有为它创建一个指向的对象。相反,我在类 B 中调用一个类方法,从 sqlite 数据库中获取一些数据,并在那里填充一个 NSMutableArray 对象。我希望能够通过将类 A 中的指针作为参数传递给方法来将指针设置为指向在类 B 方法中创建的 NSMutableArray 对象。我不能通过返回数组来做到这一点,因为我想返回 sqlite 结果。
我不知道我这样做对吗?我还没有编写完整的方法(完成后会很长),但我想知道在开始其余部分之前我是否正确地执行了指针操作。
//ClassA.m
//...
NSMutableArray *list;
[ClassB populateArrayFromSqlite:&list];
//Now do stuff with "list", which should point to the array created in populateArrayFromSqlite
//...
//ClassB.m
+(int)populateArrayFromSqlite:(NSMutableArray**)ar {
NSMutableArray *array = [[NSMutableArray alloc] init];
//Here there will be code that populates the array using sqlite (once I write it)
//And then I need to set the "list" pointer in ClassA.m to point to this array
ar = &array; //Is this how?
return resultFromSqlite;
}
我做对了吗?还是我不明白什么?我想我还不喜欢这种指针对指针的东西。在阅读了一些关于指针的一般资料后,我怀疑我会这样做,但我的一部分不明白为什么 ar 参数不能只是一个常规指针(而不是一个指向指针的指针) .
最佳答案
指向指针的指针有点深奥,是的。实现它的简单方法是在 A 中创建一个空数组,并将一个常规数组指针传递给 B,该指针将填充它。如果您坚持要在 B 中创建数组,我认为您可以这样做:
- (void) createArray: (NSMutableArray**) newArray
{
NSAssert(newArray, @"I need a pointer, sweetheart.");
*newArray = [[NSMutableArray alloc] init];
[*newArray addObject:...];
}
关于objective-c - 如何使用方法更改指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4635731/