对象没有被添加到 NSMutableArray
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;
}
在上面的程序中,我试图将学生对象添加到 StudentCount class 的 NSMutableArray
中。
之后我尝试调用 StudentCount
class 的 printStudents 方法。
学生对象未添加到 NSMutableArray
.
以上程序的输出:
Program ended with exit code: 0
哪里不对请指教
您需要分配NSMutableArray * student
。
-(void)addStudent:(Student *)stud
{
if (_student == nil) {
_student = [[NSMutableArray alloc] init];
}
[_student addObject:stud];
}
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;
}
在上面的程序中,我试图将学生对象添加到 StudentCount class 的 NSMutableArray
中。
之后我尝试调用 StudentCount
class 的 printStudents 方法。
学生对象未添加到 NSMutableArray
.
以上程序的输出:
Program ended with exit code: 0
哪里不对请指教
您需要分配NSMutableArray * student
。
-(void)addStudent:(Student *)stud
{
if (_student == nil) {
_student = [[NSMutableArray alloc] init];
}
[_student addObject:stud];
}