2011-12-21 74 views
1

如何使用NSPredicate過濾數組中的對象 - > _ title變量等於變量標題?我嘗試了下面的內容,但它沒有過濾任何東西。NSPredicate filter array

NSMutableArray *array = [[posts mutableCopy] autorelease]; 
NSString *title = [[TBForrstr sharedForrstr] stringForPostType:type]; 
[array filterUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"SELF->_title == %@", title]]]; 

回答

1

確保標題正是數組中的匹配。或者,如果你想成爲更靈活,使其不區分大小寫:

NSMutableArray *array = [[posts mutableCopy] autorelease]; 
NSString *title = [[TBForrstr sharedForrstr] stringForPostType:type]; 
[array filterUsingPredicate:[NSPredicate predicateWithFormat:@"_title == [cd]%@", title]]; 
+0

'stringWithFormat:'不是真的必要時,直接使用'predicateWithFormat:'! – V1ru8 2011-12-21 16:28:44

+0

我的不好。複製/粘貼:D。固定。 – Jeremy 2011-12-21 16:30:22

0

只需使用類似:

[NSPRedicate predicateWithFormat:@"title LIKE %@",title] 

標題應符合您的_title伊娃通過KVC

+0

_title是一個公共變量。 – 2011-12-21 16:24:07

+0

這與公共有什麼關係?但我想這只是標題LIKE%@而不是_title。 http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/Compliant.html#//apple_ref/doc/uid/20002172-BAJEAIEE – V1ru8 2011-12-21 16:27:13

1

這一個是爲我工作 - 發現串繞單引號:

NSArray *posts = [NSArray arrayWithObjects: 
    [NSDictionary dictionaryWithObjectsAndKeys: @"Cat or dog?", @"_title", nil], 
    [NSDictionary dictionaryWithObjectsAndKeys: @"I saved a file, where is it?", @"_title", nil], 
    [NSDictionary dictionaryWithObjectsAndKeys: @"How should I do this?", @"_title", nil], 
nil]; 

NSMutableArray *array = [[posts mutableCopy] autorelease]; 
NSString *title = @"Cat or dog?"; 
[array filterUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"SELF._title == '%@'", title]]]; 

NSLog(@"%@", array);