【问题标题】:Objects not getting added to the NSMutable Array [duplicate]未将对象添加到 NSMutableArray [重复]
【发布时间】: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


【解决方案1】:

您需要分配NSMutableArray * student

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

【讨论】:

  • 谢谢! @iAiator 成功了。
猜你喜欢
  • 2016-09-02
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
相关资源
最近更新 更多