2013-10-30 43 views
2

我正在使用核心数据在我的应用程序内实现简单的登录验证。 但是登录功能只适用,如果我输入正确的用户名和密码,否则我得到的例外:,我只检查如何将来自UITextField的值与CoreData值进行比较

"[__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"); 
     } 

    } 

回答

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"; 
} 
+0

嗨....我知道这是一个很长的帖子,但这已被证明对我非常有用。你介意解释这部分代码“matches = [objects objectAtIndex:0];” 。我不明白这部分是做什么的。另外,如果用户登录后又如何建议添加注销功能? –

+0

对象是一个包含关键字为employeeID的字典组的数组。所以提取相同的字符串并相应地对两个字符串进行比较。 –

+0

我得到了......我在点objectAtIndex:0处感到困惑。这行代码不仅仅意味着获取数组的第一个值吗?因此,如果创建了5个用户,那么不管核心数据是否在index:0处获取用户的登录详细信息,无论用户名和密码是否输入? –

0

你尝试检查,如果是取前访问[objects objectAtIndex:0]成功的。你应该处理NSErrors,并检查它是否不是空的nil /之前这样做。

0

在检查前是否存在matches = [objects objectAtIndex:0];是否存在coredata上的任何对象。因此,如果没有任何对象,那么会得到错误([__NSArrayI objectAtIndex:]:索引0超出空array'的界限。

删除这些行:

matches=[objects objectAtIndex:0]; 

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

是的,我理解,但我的问题是NSPredicate我检查雇员= uitextfield.text,但我不知道是什么如果他们不相等 – Nvork

+0

如果我删除那些行我得到空作为输出 – Nvork

+0

如果他们不相等你必须给用户的答案(即警报视图),表明用户没有注册或用户输入了错误的用户名或密码。 – RFG

相关问题