2012-08-05 89 views
1

我一直在試圖篩選這個數組(這是充滿NSDictionaries的)使用NSPredicate ...過濾的NSArray/NSDictionary中使用NSPredicate

我有,只是不工作的代碼,一個非常小的量.. 。

下面的代碼應該label.text改變AmyBurnett34,但它不...

NSPredicate *pred = [NSPredicate predicateWithFormat:@"id = %@", [[mightyPlistDict objectForKey:@"pushesArr"] objectAtIndex:indexPath.row]]; 

    NSLog(@"%@",pred); 

    label.text = [[[twitterInfo filteredArrayUsingPredicate:pred] lastObject] objectForKey:@"screen_name"]; 
    NSLog(@"%@",twitterInfo); 

這裏是什麼獲取NSLoged ...

2012-08-05 11:39:45.929 VideoPush[1711:707] id == "101323790" 
2012-08-05 11:39:45.931 VideoPush[1711:707] (
     { 
     id = 101323790; 
     "screen_name" = AmyBurnett34; 
    }, 
     { 
     id = 25073877; 
     "screen_name" = realDonaldTrump; 
    }, 
     { 
     id = 159462573; 
     "screen_name" = ecomagination; 
    }, 
     { 
     id = 285234969; 
     "screen_name" = "UCB_Properties"; 
    }, 
     { 
     id = 14315150; 
     "screen_name" = MichaelHyatt; 
    } 
) 

只爲頭,如果你也是這樣的NSLog ...數組爲空...

NSLog(%@,[twitterInfo filteredArrayUsingPredicate:pred]); 

回答

2

的問題是,你的謂詞是使用一個字符串比較和你的內容是使用數量。試試這個:

NSNumber *idNumber = [NSNumber numberWithLongLong:[[[mightyPlistDict objectForKey:@"pushesArr"] objectAtIndex:indexPath.row] longLongValue]]; 
NSPredicate *pred = [NSPredicate predicateWithFormat:@"id = %@", idNumber]; 
+0

完美!非常感謝! – 2012-08-05 16:29:17

-1

NSPredicate用於過濾陣列,而不是排序他們。 要排序數組,請使用NSArray的sortedArrayUsingDescriptors方法。

的一個例子:

// Define a sort descriptor based on last name. 
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];  

// Sort our array with the descriptor. 
NSArray *sortedArray = [originalArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]]; 
+0

這不回答我的問題... – 2012-08-05 16:24:54

0

你不確定「id」的值是一個字符串 - 它可能是一個NSNumber。我建議:

NSUInteger matchIdx = ...; 
NSUInteger idx = [array indexOfObjectPassingTest:^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop) 
{ 
    id obj = [dict objectForKey:@"id"]; 
    // NSLog the class if curious using NSStringFromClass[obj class]; 
    NSUInteger testIdx = [obj integerValue]; // works on strings and numbers 
    return testIdx == matchIdx; 
} 
if(idx == NSNotFound) // handle error 

NSString *screenName = [[array objectAtIndex:idx] objectForKey:@"screen_name"]; 
相關問題