2011-12-29 11 views
2

我試圖取回用下面的代碼請求:「不支持的功能表達CAST ...」使用NSPredicate使用SQLite核心數據存儲類型時

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dateModified > CAST(CAST(now(), \"NSNumber\") - %d, \"NSDate\")", (30*86400)]; 
NSFetchRequest *itemRequest = [NSFetchRequest fetchRequestWithEntityName:@"Item"]; 
[itemRequest setPredicate:predicate]; 

NSArray *items = [[self managedObjectContext] executeFetchRequest:itemRequest error:nil]; 

...爲了取項,其中'dateModified> | now() - 30天|'。問題是,上述謂詞正常工作(正確提取)直到我將我的NSPersistentDocument保存爲SQLite並重新打開文檔。當我重新打開我收到以下錯誤文件:

Unsupported function expression CAST(CAST(now(), "NSNumber") - 2592000, "NSDate")

爲什麼這個斷言正常工作,直到保存,或者如果我將文檔保存爲XML,但如果我保存爲SQLite不正常工作?有沒有辦法使用SQlite存儲類型的謂詞?

P.S.我也曾嘗試形成與下面的代碼的斷言,但得到了同樣的錯誤:

//"now()" is a function and takes no arguments 
NSExpression * now = [NSExpression expressionForFunction:@"now" arguments:[NSArray array]]; 

//CAST(now(), 'NSNumber') 
NSArray * castNowArguments = [NSArray arrayWithObjects:now, [NSExpression expressionForConstantValue:@"NSNumber"], nil]; 
NSExpression * castNow = [NSExpression expressionForFunction:@"castObject:toType:" arguments:castNowArguments]; 

//CAST(now(), 'NSNumber') [+/-] {a time interval} 
NSArray * relativeTimestampArguments = [NSArray arrayWithObjects:castNow, [NSExpression expressionForConstantValue:[NSNumber numberWithDouble:(30*86400)]], nil]; 
NSExpression * relativeTimestamp = [NSExpression expressionForFunction:@"from:subtract:" arguments:relativeTimestampArguments]; 

//CAST(CAST(now(), 'NSNumber') [+/-] {a time interval}, 'NSDate') 
NSArray * castToDateArguments = [NSArray arrayWithObjects:relativeTimestamp, [NSExpression expressionForConstantValue:@"NSDate"], nil]; 
NSExpression * castToDate = [NSExpression expressionForFunction:@"castObject:toType:" arguments:castToDateArguments]; 

NSPredicate *predicate = [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"dateModified"] 
                  rightExpression:castToDate 
                    modifier:NSDirectPredicateModifier 
                     type:NSGreaterThanOrEqualToComparison 
                    options:0]; 

回答

2

我發現我自己的解決方案......從SQLite的存儲類型獲取數據時

函數調用不受支持。只有在獲取內存數據時才能使用函數調用。爲了仍然可以使用這個斷言我只好先取數據集,然後使用過濾數組:

[allItems filteredArrayUsingPredicate:predicate]; 

希望這可以幫助別人!

+0

這就是爲什麼我的應用隨時崩潰!非常感謝! – 2017-05-18 07:27:03

0

下面的代碼摸索出剛剛好我的情況:

now() - 2592000

相關問題