我正在做一些 Objective-C 练习。我这里有两个班级,一是“主班”,一是“子班”。我需要的是获取“主类”的所有实例并将其放入数组中。我也想在我的“子类”中使用它。下面我举一个小例子。
@interface mainClass : NSObject
static NSArray *instanceObj;
@end
@implementation mainClass
//Here I used the designated initializer to initialize and add the instance to the Array
@end
@interface subClass:mainClass
@end
@implementation subClass
//Here I want to use the Array to get instances of mainClass.
@end
如果我按照上面的示例执行操作,我会收到一条警告,指出未使用静态数组,并且从数组获取数据时它为零。我还尝试在“主类”的实现文件中声明静态数组,但我无法在“子类”中使用该数组。请为我提供一个解决方案并帮助我理解这个概念。
几个问题:
将
static
移至 @interface
之外,并移至 @implementation
上方的 .m 文件中。你显然需要做那个
NSMutableArray
,而不是NSArray
。预先警告,通过向该数组添加对象,会建立对这些对象的强引用,并且在将它们从数组中删除之前,它们不会被释放。
顺便说一句,您可能还想遵守 Cocoa 命名约定,使用
MainClass
和 SubClass
而不是 mainClass
和 subClass
。更好的是,使用有意义的名称。