2012-03-22 31 views
6

這真是讓我瘋狂。iOS Core Data如何使用謂詞正確比較字符串文本?

我有2個實體使用NSString作爲唯一屬性。

創建一個比較NSStrings的謂詞的正確方法是什麼?

目前我有: [NSPredicate predicateWithFormat:@「unique =%@」,uniqueValue];

我有一種感覺,這比較指針地址,而不是實際的字符串值,但我無法證實這一點。我需要返回肯定字符串匹配。

-(BOOL)uniqueEntityExistsWithEnityName:(NSString*)entityName UniqueKey:(NSString*) uniqueKey UniqueValue:(NSString*)uniqueValue SortAttribute:(NSString*)sortDescriptorAttribute ManagedObjectContext:(NSManagedObjectContext*) context; 
{ 
    BOOL returnValue = NO; 

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName]; 

//what is the correct predates to compare the text an string core data property against a passed in string? 
    request.predicate = [NSPredicate predicateWithFormat:@"unique= %@", uniqueValue]; 

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:sortDescriptorAttribute ascending:YES]; 
    request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 

    NSError *error = nil; 
    NSArray *matches = [context executeFetchRequest:request error:&error]; 
    if (!matches) 
    { 
     NSLog(@"Error: no object matches"); 
    } 
    else if([matches count] > 1) { 
     NSLog(@"Error: More than one object for unique record"); 
     returnValue = YES; 

    } else if ([matches count] == 0) { 
     returnValue = NO; 
    } else { 
     returnValue = YES; 
    } 

    return returnValue; 
} 
+0

您是否有感覺或實際問題?你的代碼看起來沒問題。你的數據是從sqlite數據庫中提取的,它應該如何匹配指針地址? – 2012-03-23 05:38:28

回答

9

單個等號在編碼方面甚至不是比較器。

我打算假設unique是一個NSManagedObject屬性。

[NSPredicate predicateWithFormat:@"unique LIKE %@", uniqueValue]; 

請注意,這是區分大小寫的。如果你想讓它變得不敏感,那麼你可以在LIKE之後放置[c]。

+0

謝謝凱文,我會測試一下! – 2012-03-22 15:30:51

+12

單個等號完美適用於NSPredicate。 – 2012-03-23 05:40:53

+0

哦!我想你是對的!哇,這似乎很奇怪(因爲編碼單個等號的任何其他地方都是一項任務)。 – 2012-03-23 14:03:26

7

我沒有看到您的謂詞有問題。如果你想匹配確切的字符串,單個=是完美的。如果你不需要通配符匹配,你不需要較慢的LIKE。 (Predicate Format String Syntax

但是,您的代碼存在問題,並且可能會導致您假設不正確。你的if/then/else,或者至少是第一條消息是錯誤的。如果您的提取沒有返回數組,這意味着提取失敗,但這並不意味着提取沒有返回對象。

應該更多這樣的:

if (!matches) 
{ 
    NSLog(@"Error: couldn't execute fetch request %@", error); 
} 
else if([matches count] > 1) { 
    NSLog(@"Error: More than one object for unique record"); 
    returnValue = YES; 
} else if ([matches count] == 0) { 
    NSLog(@"couldn't match objects"); 
    returnValue = NO; 
} else { 
    // [matches count] == 1 
    NSLog(@"matched one object"); 
    returnValue = YES; 
} 

哦,我會改變的條件的順序。在我看來,像(!匹配),([匹配計數] == 1),([匹配計數] == 0)的結構,(其他)更有意義,並且它更容易被讀取。你把最重要的(因爲它是你真正想要的)條件放在最後的「匿名」中。