第二次使用方法给我一个错误(IOS)

时间:2016-02-26 18:18:46

标签: ios objective-c

我在目标c(Xcode)中编写此应用程序。

当我第一次使用方法时一切顺利,但是当我第二次使用它时它会给我一个错误。

我尝试调试它,如果([tutor.userName isEqualToString:userName])

,那么错误就会在行中添加tutor

这是错误:

  

- [__ NSCFConstantString userName]:发送到的无法识别的选择器   实例0xad14c 2016-02-26 20:10:44.043项目[1258:35474] ***   由于未捕获的异常而终止应用程序   'NSInvalidArgumentException',原因:' - [__ NSCFConstantString   userName]:无法识别的选择器发送到实例0xad14c'

这是我的代码:

- (IBAction)addToFavorite:(id)sender {
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSString * userName = delegate.delegateStr;
    Student * student = [[Model instance]getStudentByUserName:userName];
    [student addTutor:self.tutor.userName];

    UIStoryboard* sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    FavoritesTableViewController * ftvc = [sb instantiateViewControllerWithIdentifier:@"favoritesTableViewController"];
    ftvc.favTutors = student.favTutors;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshTable" object:nil userInfo:nil];

}



-(void)addTutor:(NSString*)userName {
    BOOL check = YES;
    for (Tutor * tutor in self.favTutors) {
        if([tutor.userName isEqualToString:userName])
            check = NO;
    }
    if(check)
        [self.favTutors addObject:userName];
}

请帮助!!

感谢。

2 个答案:

答案 0 :(得分:2)

问题出现在我添加评论的行。您正在向NSString个对象添加Tutor个对象。并且在第二次调用此方法时,在for循环中,导师实际上是NSString并且您尝试调用tutor.userName并且它在NSString对象中不存在。

-(void)addTutor:(NSString*)userName {
    BOOL check = YES;
    for (Tutor * tutor in self.favTutors) {
        if([tutor.userName isEqualToString:userName])
            check = NO;
    }
    if(check)
        [self.favTutors addObject:userName]; //problem here!!!!
}

我的建议是创建教师对象并将其添加到您的阵列中。

-(void)addTutor:(NSString*)userName {
    BOOL check = YES;
    for (Tutor * tutor in self.favTutors) {
        if([tutor.userName isEqualToString:userName])
            check = NO;
    }
    if(check)
    {
        // create Tutor object and add it to array dont add NSString directly
    }
}

答案 1 :(得分:2)

由于您在username数组中添加了favTutors而不是Tutor的对象,因此失败了。因此,当您添加第一个对象,然后下次枚举self.favTutors时,您实际上有一个不会响应username属性的字符串对象。