Objective C:class 对象数组 属性

Objective C: array of class object as property

是否可以在 Objective-C class 中将另一个 class 的实例数组存储为 属性?

简单示例:我有一个名为 "Classroom" 的 class 和一个名为 "Students" 的 class。

@interface Student
    @property int m_id;
@end

...

@interface Classroom
    @property Student *m_students[20]; // this causes a compilation error: property cannot have an array or function type 'Student *[20]'
@end

我该怎么做?

改用NSArrayNSMutableArray

@interface Classroom
    @property NSMutableArray *m_students; // this causes a compilation error.
@end

然后在您的实施中:

Student *student = [[Student alloc] init];
[self.m_students addObject:student];

NSArray(及其子类 NSMutableArray)可以包含任何 Objective-C 对象。您甚至可以将它们混合在同一个数组中。