【发布时间】:2016-10-16 07:13:35
【问题描述】:
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 类的NSMutableArray。
之后,我尝试调用 StudentCount 类的 printStudents 方法。
学生对象不会添加到NSMutableArray。
上述程序的输出:
程序以退出代码结束:0
请告知我哪里出错了。
【问题讨论】:
-
不要将包含 student_s_ 的数组称为“学生”。称其为学生。隐藏在你的代码中会让你和其他人感到困惑。
-
你错过了每个学生的初始化调用。
标签: ios objective-c nsmutablearray nsarray