2

我正在使用核心数据在我的应用程序中实现简单的登录身份验证。但是登录功能只有在我输入正确的用户名和密码时才有效,否则我会遇到异常:

"[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'"

我知道这是因为我的代码不正确(即,我只检查是否相等)。但我不知道如何检查不平等。

任何人都可以帮助我使用核心数据执行登录身份验证...

代码 :

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Employee"
                                                      inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(employeeID = %@)",
                             self.employeeId.text];
    [request setPredicate:pred];
    NSManagedObject *matches = nil;
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];

    matches=[objects objectAtIndex:0];

    NSLog(@"qweertyuio%@",[matches valueForKey:@"employeeID"]);

    if ([objects count] == 0) 
    {
        status.text = @"No matches";
    }
    else
    {
        NSString *str=self.employeeId.text;
        NSString *str1=[matches valueForKey:@"employeeID"];
        matches=[objects objectAtIndex:0];
        if ([str isEqualToString:str1]) 
        {
            NSLog(@"hai");
        }

    }
4

3 回答 3

2

试试下面这样: -

NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] > 0) {
    matches=[objects objectAtIndex:0];
   NSLog(@"qweertyuio%@",[matches valueForKey:@"employeeID"]);
NSString *str=self.employeeId.text;
    NSString *str1=[matches valueForKey:@"employeeID"];
 matches=[objects objectAtIndex:0];
    if ([str isEqualToString:str1]) {
   NSLog(@"hai");
    }
}    
else
{
status.text = @"No matches";
 }
于 2013-10-30T10:59:07.073 回答
0

[objects objectAtIndex:0]您在检查获取是否成功之前尝试访问。在执行此操作之前,您应该处理NSErrors并检查它是否nil不为空。

于 2013-10-30T10:45:32.950 回答
0

matches = [objects objectAtIndex:0];检查coredata. 因此,如果没有任何对象,则会得到错误([__NSArrayI objectAtIndex:]:索引 0 超出空array') 的界限。

删除这些行:

matches=[objects objectAtIndex:0];

NSLog(@"qweertyuio%@",[matches valueForKey:@"employeeID"]);
于 2013-10-30T10:46:51.237 回答