2

我正在使用目标 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 参数不能只是一个常规指针(而不是指向指针的指针) .

4

2 回答 2

6

指向指针的指针有点 escheric,是的。简单的方法是在 A 中创建一个空数组,然后将一个常规数组指针传递给 B 来填充它。如果您坚持在 B 中创建数组,我认为您可以这样做:

- (void) createArray: (NSMutableArray**) newArray
{
    NSAssert(newArray, @"I need a pointer, sweetheart.");
    *newArray = [[NSMutableArray alloc] init];
    [*newArray addObject:...];
}
于 2011-01-08T19:54:22.443 回答
2

像这样更改指向对象的指针在 Objective-C 中是相当少见的。我们看到这样的事情的主要时间是当一个方法有可能失败时,此时我们将传递一个指向NSError引用的指针。例如,NSFileManager's - (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

更常见的方法是让方法返回数组:

NSMutableArray * list = [ClassB mutableArrayFromSQLite];
于 2011-01-08T20:07:16.583 回答