ios - 无法识别的选择器已发送到实例Objective-C

标签 ios objective-c arrays bitwise-operators

我收到错误:

由于未捕获的异常而终止应用程序
“NSInvalidArgumentException”,原因:“-[__ NSCFConstantString
subjectType]:无法识别的选择器已发送到实例

我正在尝试根据自己正在学习的学科类型将应用中的学生分类为数组。

AMStudent* student = [[AMStudent alloc] init];

NSMutableArray* studentArray = [[NSMutableArray alloc] init];

NSArray* studentNameArray = [NSArray arrayWithObjects: @"Student1",  @"Student2", @"Student3", @"Student4", @"Student5", @"Student6", @"Student7", @"Student8", @"Student9", @"Student10", nil];

[studentArray addObjectsFromArray:studentNameArray];

for (NSInteger i = 0; i < [studentNameArray count]; i++) {

    student.name = [studentNameArray objectAtIndex: i];
    [student randomAnswer];
    NSLog(@"%@", student.description);

}

NSMutableArray* techArray = [NSMutableArray array];
NSMutableArray* humArray = [NSMutableArray array];

for (AMStudent* stud in studentArray){

    if ((stud.subjectType & AMStudentSubjectTypeDevelopment) | (stud.subjectType & AMStudentSubjectTypeMath)) {
        [techArray addObject:stud];
    } else {
        [humArray addObject:stud];
    }
}

我无法弄清楚我到底在做什么错,因为它在此阶段崩溃:
if ((stud.subjectType & AMStudentSubjectTypeDevelopment) | (stud.subjectType & AMStudentSubjectTypeMath)) {
        [techArray addObject:stud];
    } else {
        [humArray addObject:stud];
    } 

最佳答案

您使用以下命令填充studentArray:

[studentArray addObjectsFromArray:studentNameArray];

因此studentArray包含NSString实例。然后,您尝试使用以下方法处理阵列:
for (AMStudent* stud in studentArray){

这样做不是而不是神奇地将NSString中的studentArray实例转换为AMStudent实例。您现在不会出错,因为studentArray可以包含任何类型的对象,因此编译器只相信您知道自己在做什么,并将对NSString的引用放入stud中。然后执行以下操作:
   if ((stud.subjectType ...

这就要求stud引用一个AMStudent对象,但它没有,它引用了一个(常量)字符串,因此您得到以下错误:

NSInvalidArgumentException',原因:'-[ __NSCFConstantString subjectType]:无法识别的选择器已发送到实例

无需将学生的姓名复制到studentArray中,您需要创建AMStudent实例并将其添加到数组中。您是否打算在第一个循环中这样做?

高温超导

关于ios - 无法识别的选择器已发送到实例Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40152271/

相关文章:

objective-c - 实现开放行动

ios - 单例数组不会存储数据模型

ios - 如何在水平分页 ScrollView 中添加日期选择器?

python - 有没有办法从Python中的单独文本文件中选择某些元素?

c - AVR gcc,奇怪的数组行为

iphone - facebook登录后UILabel变为null(UILabel不更新)

iOS IAP - 如何区分 "restoring done, but not purchased before"状态

php - 如何在php中访问嵌套数组

ios - 在iOS中,是否可以获取当前轨道的波形或频谱数据?例如: equalizer

ios - UIImageView+animatedGIF总是LOOPS