2016-06-20 6 views
2
NSArray *arrData = [NSArray arrayWithObjects: 
        @"cloud,country,plant", 
        @"country,cloud,plant", 
        @"country,plant,cloud", 
        @"clouds,country,plant" 
        ,@"country,clouds,plant", 
        nil]; 

Von oben NSArray möchte ich Objekte, dieNSPredicate für genaue Übereinstimmung

ich unten Code versucht, ein Wort "Wolke" mit

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(self beginswith %@ OR self contains[CD] %@)",@"cloud",@",cloud"]; 
NSArray *arrResult = [arrData filteredArrayUsingPredicate:predicate]; 

Aber es gibt alle fünf Objekte in arrResult. Aber ich brauche nur 3 (0,1,2) Objekte.

+0

jedes Objekt im Array ist Komma separated Wert? –

+0

Sie könnten eine 'NSRegularExpression' mit einem' MATCHES'-Prädikat verwenden und nach etwas wie Cloud am Ende der Zeichenfolge oder Wolke suchen, gefolgt von einem Nicht-Buchstaben-Zeichen. – Larme

+0

@ kirtimali. Ja – kb920

Antwort

2

Versuchen:

NSPredicate* predicate = [NSPredicate predicateWithBlock:^(NSString* string, NSDictionary* options){ 

    NSArray* array = [string componentsSeparatedByString:@","]; 

    return [array containsObject:@"cloud"]; 

}]; 
+0

Wenn "cloud" am Ende ist, sollte es nicht funktionieren, nicht? – Larme

+0

Ja, das war dumm. dieses ist besser –

+0

Dank @AndreyChernukha – kb920

1

Try Code unten,

Es wird funktionieren,

NSPredicate *hsPredicate = [NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) { 
     NSArray *sepretArray =[((NSString*)evaluatedObject) componentsSeparatedByString:@","]; 
     NSPredicate *subPredicate = [NSPredicate predicateWithFormat:@"self == %@",@"cloud"]; 
     return ([sepretArray filteredArrayUsingPredicate:subPredicate].count > 0); 

    }]; 
    NSArray *arrResult = [arrData filteredArrayUsingPredicate:hsPredicate]; 
1

Das man die trick.But tun, ich weiß nicht, ob es das ist, effiziente Art und Weise dies zu tun.

NSArray *arrData = [NSArray arrayWithObjects: 
        @"cloud,country,plant", 
        @"country,cloud,plant", 
        @"country,plant,cloud", 
        @"clouds,country,plant" 
        ,@"country,clouds,plant", 
        nil]; 

NSMutableArray *resArray = [[NSMutableArray alloc]init]; 
for(NSString *tempString in arrData) 
{ 
    NSArray *cache = [tempString componentsSeparatedByString:@","]; 
    if([cache containsObject:@"cloud"]) 
     { 
     [resArray addObject:tempString]; 
     } 
}