2013-08-21 187 views
1

我想從另一個濾鏡陣列陣列下面是我的代碼片段字符串長度關係

NSMutableArray *filteredArray = [[NSMutableArray alloc] initWithCapacity:1]; 
    [wordsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) 
    { 
     NSString *currentWord = (NSString *)obj; 
     if(([currentWord length]>=4 && [currentWord length]<=6) && [currentWord rangeOfString:@" "].location == NSNotFound) 
     { 
      [filteredArray addObject:currentWord]; 
     } 
    }]; 

我的代碼是完全可以作爲我的預期。我覺得使用filteredArrayUsingPredicate:是比我的代碼更優化的解決方案。任何人都可以讓我知道如何爲我的代碼編寫NSPredicate。我跟很多的問題,但這個問題非是給我準確的答案來代替[currentWord長度]> = 4 & & [currentWord長度] < = 6)& & [currentWord rangeOfString:@」「] .location == NSNotFound與NSPredicate。

請提前告訴我最佳解決方案。

回答

4

嘗試像謂詞:

NSPredicate *p = [NSPredicate predicateWithFormat:@"length >= 4 AND length <= 6 AND NOT SELF CONTAINS ' '"]; 
+0

感謝北斗星,這是完美的工作。你能否建議我參考一下學習謂詞相關的東西。 – ajay

+0

Apple指南是https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/predicates.html#//apple_ref/doc/uid/TP40001798-SW1 – Wain

2

隨着謂詞的一個清晰的解決方案。但它不是更快(你說優化)。即使你重複使用謂詞!

我爲我的2GHz i7 MacBook Pro寫了一個小測試。解決辦法:
1.000.000次濾波的陣列:

  • 每當一個新的謂詞:39.694秒
  • 重用謂詞:17.784秒
  • 您的代碼:2.174秒

很大的區別不是嗎?

這裏是我的測試代碼:

@implementation Test 
- (void)test1 
{ 
    int x = 0; 
    NSArray *array = @[@"a", @"bb", @"ccc", @"dddd", @"eeeee", @"ffffff", @"ggggggg", @"hh hh", @"ii ii"]; 
    for (int i = 0; i < 1000000; i++) { 
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"length >= 4 AND length <= 6 AND NOT self CONTAINS ' '"]; 
     x += [array filteredArrayUsingPredicate:predicate].count; 
    } 
    NSLog(@"%d", x); 
} 

- (void)test2 
{ 
    int x = 0; 
    NSArray *array = @[@"a", @"bb", @"ccc", @"dddd", @"eeeee", @"ffffff", @"ggggggg", @"hh hh", @"ii ii"]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"length >= 4 AND length <= 6 AND NOT self CONTAINS ' '"]; 
    for (int i = 0; i < 1000000; i++) { 
     x += [array filteredArrayUsingPredicate:predicate].count; 
    } 
    NSLog(@"%d", x); 
} 

- (void)test3 
{ 
    int x = 0; 
    NSArray *array = @[@"a", @"bb", @"ccc", @"dddd", @"eeeee", @"ffffff", @"ggggggg", @"hh hh", @"ii ii"]; 
    for (int i = 0; i < 1000000; i++) { 
     NSMutableArray *filteredArray = [NSMutableArray array]; 
     [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) 
     { 
      NSString *currentWord = (NSString *)obj; 
      if(([currentWord length]>=4 && [currentWord length]<=6) && [currentWord rangeOfString:@" "].location == NSNotFound) 
      { 
       [filteredArray addObject:currentWord]; 
      } 
     }]; 
     x += filteredArray.count; 
    } 
    NSLog(@"%d", x); 
} 
+0

它如何處理大量數據只能枚舉一次?另外,它將如何執行相對於predicateWithBlock:? –

+0

使用長度介於0和9個字母之間的10.000個隨機字符串進行測試。每次測試重複10.000次。每次創建謂詞:165.828秒,重複使用謂詞:167.147秒,enumerateObjectsUsingBlock:20.235秒,filteredArrayUsingPredicate:23.974秒 – Obenland

+0

@Xean我欣賞你的新思路讓我試試... – ajay