我正在使用核心数据在我的应用内部实现简单的登录身份验证。 但登录功能只有在我输入正确的用户名和密码时才有效,否则我会收到例外:
"[__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");
}
}
答案 0 :(得分: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";
}
答案 1 :(得分:0)
在检查提取是否成功之前,您尝试访问[objects objectAtIndex:0]
。在执行此操作之前,您应该处理NSErrors
并检查它是否nil
/不是空的。
答案 2 :(得分:0)
在检查matches = [objects objectAtIndex:0];
上是否存在任何对象之前,您已coredata
。因此,如果没有任何对象,则会得到错误([__NSArrayI objectAtIndex:]:
索引0超出空array
'的边界。)
删除以下行:
matches=[objects objectAtIndex:0];
NSLog(@"qweertyuio%@",[matches valueForKey:@"employeeID"]);