2012-04-15 88 views
4

目前我正在循环查看所有计划的本地通知,以便根据userInfo字典对象中的值查找“匹配”。当我设置了30多个本地通知时,这看起来非常缓慢。有没有一种方法可以访问单个本地通知而无需遍历数组?在没有for循环的情况下在scheduledLocalNotifications数组中找到UILocalNotification?

以下是我有:

NSArray *notificationArray = [[UIApplication sharedApplication]  scheduledLocalNotifications]; 
UILocalNotification *row = nil; 
for (row in notificationArray) { 
      NSDictionary *userInfo = row.userInfo; 
      NSString *identifier = [userInfo valueForKey:@"movieTitle"]; 
      NSDate *currentAlarmDateTime = row.fireDate; 
if([identifier isEqualToString:myLookUpName]) { 
NSLog(@"Found a match!"); 
} 
} 

下面是我想:

NSArray *notificationArray = [[UIApplication sharedApplication]  scheduledLocalNotifications]; 
UILocalNotification *row = " The row in notificationArray where [userInfo valueForKey:@"movieTitle"]=myLookUpName" ; 

回答

8

您可能能够使用谓词这一点,但我没有测试它:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userInfo.movieTitle = %@", myLookUpName]; 

然后使用该谓词来过滤数组并抓取第一个元素:

UILocalNotification *row = [[notificationArray filteredArrayUsingPredicate:predicate]objectAtIndex:0]; 

再次,这是未经测试,可能无法正常工作。

编辑

如果不工作,你可以使用一个试块:

UILocalNotification *row = [[notificationArray objectsAtIndexes:[notificationArray indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop){ 
    return [[[obj userInfo]valueForKey:@"movieTitle"] isEqualToString:myLookUpName]; 
}]]objectAtIndex:0]; 
+0

你能向我解释什么是在试块码怎么回事?我尝试将它“复制并粘贴到”我的代码中,但它会产生一个错误:将'id(^)(id,NSUInteger,BOOL *)'发送到类型为'BOOL(^)的参数的不兼容块指针类型(id, NSUInteger,BOOL *)' – Eric 2012-04-16 01:40:08

+1

@Eric:不知道你为什么会得到这个错误。 http://www.fieryrobot.com/blog/2010/06/20/being-a-blockhead/可能有助于确定问题。 – 2012-04-16 13:46:32

+0

在这里真正来临,但对于谁在这个伟大的答案绊倒,但由代码中的错字抛出的任何其他人,试试这个: ''' UILocalNotification * row = [[notificationArray objectsAtIndexes:[notificationArray indexesOfObjectsPassingTest:^ (id obj,NSUInteger idx,BOOL * stop){ return [[[obj userInfo] valueForKey:@“movieTitle”] isEqualToString:myLookUpName]; }]] objectAtIndex:0]; ''' – 2015-12-02 10:28:50

相关问题