【问题标题】:Objective C: array of class object as propertyObjective C:类对象数组作为属性
【发布时间】:2015-11-12 10:55:59
【问题描述】:

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

简单示例:我有一个名为“教室”的班级和一个名为“学生”的班级。

@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

我怎样才能做到这一点?

【问题讨论】:

    标签: objective-c arrays class properties


    【解决方案1】:

    改用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 对象。您甚至可以将它们混合在同一个数组中。

    【讨论】:

    • 谢谢!所以如果我想让我的数组中有 20 个学生,是否应该这样做 20 次?
    • 是的,你必须做 20 次
    • offcourse 使用循环/递归 (: 并从 NSObject 继承两个类
    猜你喜欢
    • 2013-10-04
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多