如何检查PList,iPhone中是否已存在数据或对象?

时间:2011-04-12 10:53:07

标签: iphone objective-c

我可以在PList中成功添加和删除对象或数据,但我想知道PList中已存在数据或对象。我的代码是

NSUInteger countObjectsFromPList;
countObjectsFromPList = [[mdict allKeys] count];
NSLog(@"objects in PList %d", countObjectsFromPList);
for(int i=0; i <= countLawsFromPList; i++){
NSLog(@"\n\n\n%d\n\n\n", i);
//if([objectName isEqualToString:[[mdict allKeys] objectAtIndex:i]])
if(objectName ==[[mdict allKeys] objectAtIndex:i]){
NSLog(@"Already exists");
//NSLog("String is equal");
}
else { 
NSLog(@"Added to Favorites");
} 
}

请任何人帮我解决这个问题。感谢

2 个答案:

答案 0 :(得分:3)

id object = [mdict objectForKey:key];
BOOL exists = (object != nil);

编辑:显然这还不够清楚。 基本上objectForKey你只是在告诉字典“你能不能给我一个关键字key的对象?”如果该对象存在于该键,则返回值将为非零。否则它将是零。这就是为什么你检查object != nil以便知道你的密钥字典中是否存在该对象的原因。 去喝更多的咖啡

答案 1 :(得分:2)

感谢所有代码答案,但结果证明对我没有帮助。我纠正了我的代码:

mdict = [[NSMutableDictionary alloc] initWithContentsOfFile:[self doccumentspath]];
NSUInteger countObjectsFromPList = [[mdict allKeys] count];
NSLog(@"Objects in PList %d", countObjectsFromPList);

for(int i=0; i < countObjectsFromPList; i++){
  NSLog(@"\n\n\n%d\n\n\n", i);
  NSLog(@"from viewWillAppear- Object Name- %@", object);
  if([object isEqualToString:[[mdict allKeys] objectAtIndex:i]]){   
    NSLog(@"Already exists");       
    exists = YES;
    NSLog(@"The value of the bool is %@\n", (exists ? @"YES" : @"NO"));
  }
}

我必须要删除=循环中的for。现在它工作正常。