2011-02-27 88 views
2

我試圖獲取核心數據中實體中屬性的最大值。蘋果有一個很好的例子here如何做到這一點;但是,它不適合我。我在我的moc中有10個對象,下面的代碼總是返回一個大小爲0的數組。任何人都可以告訴我我做錯了什麼?謝謝!獲取實體中值的最大值

NSManagedObjectContext* moc = [self managedObjectContext]; 

    // set the idx to the maximum value 
    NSFetchRequest* request = [[NSFetchRequest alloc] init]; 
    NSEntityDescription* entity = [NSEntityDescription entityForName:@"Transaction" 
              inManagedObjectContext:moc]; 
    [request setEntity:entity]; 

    // Specify that the request should return dictionaries. 
    [request setResultType:NSDictionaryResultType]; 

    // Create an expression for the key path. 
    NSExpression* keyPathExpression = [NSExpression expressionForKeyPath:@"idx"]; 

    // Create an expression to represent the minimum value at the key path 'creationDate' 
    NSExpression* maxExpression = [NSExpression expressionForFunction:@"max:" 
                  arguments:[NSArray arrayWithObject:keyPathExpression]]; 

    // Create an expression description using the minExpression and returning a date. 
    NSExpressionDescription* expressionDescription = [[NSExpressionDescription alloc] init]; 

    // The name is the key that will be used in the dictionary for the return value. 
    [expressionDescription setName:@"maxIdx"]; 
    [expressionDescription setExpression:maxExpression]; 
    [expressionDescription setExpressionResultType:NSInteger32AttributeType]; 

    // Set the request's properties to fetch just the property represented by the expressions. 
    [request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]]; 

    // Execute the fetch. 
    NSError* error = nil; 
    NSArray* objects = [moc executeFetchRequest:request error:&error]; 
    if (objects == nil) { 
    // Handle the error. 
    } 
    else { 
    if ([objects count] > 0) { 
     int newIdx = [[[objects objectAtIndex:0] valueForKey:@"maxIdx"] intValue] + 1; 
     [self setPrimitiveIdx:[NSNumber numberWithInt:newIdx]]; 
    } else { 
     [self setPrimitiveIdx:[NSNumber numberWithInt:1]]; 
    } 
    } 

回答

1

你的代碼看起來我的權利,所以請檢查下列

  1. 事實上,你在你的商店交易對象。只需從相同的上下文進行正常的獲取。

  2. 在設置上下文之前,你可以這樣做嗎?

  3. 檢查,看看是否有什麼錯誤的 - 只要登錄[error localDescription]

  4. 是對IDX NSInteger32AttributeType吧?

  5. idx拼寫正確嗎?是交易嗎?意思是,它們與你的模型相符。

PS:它不會不管的結果,但希望你有釋放從代碼示例

+0

+1打我給它。我認爲最可能的錯誤是拼寫錯誤'交易'或關鍵路徑。我會在沒有表達式的情況下運行抓取並查看返回的結果。 – TechZen 2011-02-27 16:26:19

+0

是的,我檢查過拼寫和其他幾次。商店中有10個交易對象,idx是一個整數32.我在應用程序中使用垃圾收集,所以發佈應該沒有關係。我會檢查錯誤日誌。 – Cayden 2011-02-27 20:51:12

+0

一旦持久性存儲已被保存,看起來上述內容將起作用;但在此之前。儘管如此,我仍然可以在一個替代解決方案中完全使用它。 – Cayden 2011-02-28 15:01:20