1

Is it possible in an Objective-C class to store an array of instances of another class as a property?

Simple example: I have a class called "Classroom" and a class called "Students".

@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

How can I do the equivalent of this?

1 Answer 1

0

Use a NSArray or NSMutableArray instead:

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

Then in your implementation:

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

NSArray (and it's subclass NSMutableArray) can contain any Objective-C object. And you can even mix them in the same array.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! So if I want 20 students in my array, should this be done 20 times?
Yes you have to do 20 times
offcourse using a loop/recursion (: and inherit both of the class from NSObject

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.