Harish Harish - 1 month ago 6
Objective-C Question

Objects not getting added to the NSMutable Array

Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject
@property NSInteger age;
@property NSString *name;
@end

Student.m

#import "Student.h"
@implementation Student
@end

StudentCount.h

#import <Foundation/Foundation.h>
#import "Student.h"
NSMutable
@interface StudentCount : NSObject
@property NSMutableArray<Student *> *student;
-(void)addStu:(Student *)stud;
-(void)printStudents;
@end

StudentCount.m

#import "StudentCount.h"

@implementation StudentCount
-(void)addStu:(Student *)stud{
[_student addObject:stud];
}
-(void)printStudents{
for(Student *s in _student){
NSLog(@"%li",s.age);
NSLog(@"%@",s.name);
}
}
@end

Main.m

#import <Foundation/Foundation.h>
#import "Student.h"
#import "StudentCount.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *student1=[Student alloc];
student1.age=10;
student1.name=@"Nirmal";

Student *student2=[Student alloc];
student2.age=12;
student2.name=@"Anand";

StudentCount *stCount=[StudentCount alloc];
[stCount addStu:student1];
[stCount addStu:student2];

[stCount printStudents];


}
return 0;
}


In the above program, I tried to add the student object to the NSMutableArray of the StudentCount class.
After that I tried to call the printStudents method of the StudentCount class.
The student objects are not added to the NSMutableArray.

Output of the above program: Program ended with exit code: 0

Please advise where I am going wrong.

Answer

You need to allocate the NSMutableArray *student.

    -(void)addStu:(Student *)stud{
    if (_student == nil) {
        _student = [[NSMutableArray alloc] init];
    }
    [_student addObject:stud];
    }
Comments