我正在处理一个非常基本的问题,我需要比较两个字典键,但是当我这样做时,它并没有给我正确的答案,不知怎的,我没有创建逻辑。
所以我有一个plist数组的字典和json数组从服务器传入 如果plist中存在事件,如果不做其他事情,我想比较它们;
问题:
根据我的逻辑,如果plist中的两个事件等于来自服务器的其他两个事件,如果每个来自服务器的字典应该打印逻辑,那么在这种情况下总共2次,但在我的代码中它被打印4次。基本上它每次都满足条件。
的NSLog:
evreka find the id
evreka find the id
evreka find the id
evreka find the id
来源: 在一个plist;
createList (
{
"end_date" = "2013-07-24";
ends = "13:07:00";
"event_id" = 173;
"event_name" = Static;
location = Asdad;
"root_folder" = "dadapof@gmail.com";
"start_date" = "2013-07-24";
starts = "13:07:00";
"user_id" = 13;
},
{
"end_date" = "2013-07-25";
ends = "13:08:00";
"event_id" = 174;
"event_name" = "Event Delete";
location = Asdsad;
"root_folder" = "dadapof@gmail.com";
"start_date" = "2013-07-25";
starts = "13:08:00";
"user_id" = 13;
}
)
此服务器来自
responseobj (
{
"end_date" = "2013-07-24";
ends = "13:07:00";
"event_id" = 173;
"event_name" = Static;
location = Asdad;
"root_folder" = "dadapof@gmail.com";
"start_date" = "2013-07-24";
starts = "13:07:00";
"user_id" = 13;
},
{
"end_date" = "2013-07-25";
ends = "13:08:00";
"event_id" = 174;
"event_name" = "Event Delete";
location = Asdsad;
"root_folder" = "dadapof@gmail.com";
"start_date" = "2013-07-25";
starts = "13:08:00";
"user_id" = 13;
}
)
代码:
比较代码;
if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
createList= [NSMutableArray arrayWithContentsOfFile:dataPath];
NSLog(@"createList %@",createList);
NSLog(@"responseobj %@",responseObj);
//compare plist and response object
for (int i=0; i<[responseObj count]; i++) {
NSDictionary *dataDict = [responseObj objectAtIndex:i];
NSString *event_name =[dataDict objectForKey:@"event_name"];
//NSString *event_id =[dataDict objectForKey:@"event_id"];
BOOL eventExistInPlist=NO;
for (int j=0; j<[createList count]; j++) {
NSDictionary *createDict = [createList objectAtIndex:i];
//NSString *create_id =[createDict objectForKey:@"event_id"];
NSNumber *create_id =[createDict objectForKey:@"event_id"];
if ([[dataDict objectForKey:@"event_id"] isEqual:[createDict objectForKey:@"event_id"]]) {
// if (create_id==event_id) {
NSLog(@"evreka find the id");
我尝试了什么: 我试图将它们比作字符串(isEqualtoString),数字(==)和isEqual:方法,它们都失败了。
我做错了什么?
答案 0 :(得分:3)
在
NSDictionary *createDict = [createList objectAtIndex:i];
^----- HERE
您使用了错误的索引,内循环应该是j
而不是i
。
答案 1 :(得分:1)
Martin R的回答是您的问题所在。我会改变你的逻辑虽然包括Objective-C快速枚举而不是++循环的标准。我还将第二个for循环分离为BOOL方法以便于阅读
for (NSDictionary *dataDict in responseObj) {
NSString *event_name =[dataDict objectForKey:@"event_name"];
if ([self matchFoundForEventId:event_name]) {
NSLog(@"Match found");
}
}
-(BOOL)matchFoundForEventId:(NSString *)eventId {
for (NSDictionary *dataDict in createList) {
NSString *createEvent = [dataDict objectForKey:@"event_id"];
if ([eventId isEqualToString:createEvent]) {
return YES;
}
}
return NO;
}