2014-05-05 23 views
0

UITableViewController顯示遊戲中的分數。
得分將顯示1,5,1,13
他們保存的順序,但看了他們剛剛開始改變順序的分數兩三次的分數。該分數將顯示
5,1,1,13或1,13,1,5
我使用此代碼爲什麼每次在UITableViewController中以不同的順序顯示我的Core Data?

-(void)saveDate 
{ 
    NSManagedObjectContext *context = [self managedObjectContext]; 
    NSManagedObject *newScore = [NSEntityDescription insertNewObjectForEntityForName:@"Scores" inManagedObjectContext:context]; 
    NSNumber *theScore = [[NSNumber alloc]initWithInt:self.score]; 
    [newScore setValue:theScore forKeyPath:@"score"]; 
} 

我的實體名稱爲 「成績」 拯救分數和我有有其中一個屬性稱爲「得分」。
我加載Core DataTableView內部ViewDidLoad

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Scores"]; 
    self.scores = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy]; 
    [self.tableView reloadData]; 
} 

self.scores是@propertyNSMutableArray,我將數據複製到這樣我在NumberOfRows使用我使用[self.scores count];
這是我管理的對象上下文的代碼。

 - (NSManagedObjectContext *)managedObjectContext 
{ 
    NSManagedObjectContext *context = nil; 
    id delegate = [[UIApplication sharedApplication] delegate]; 
    if ([delegate performSelector:@selector(managedObjectContext)]) { 
     context = [delegate managedObjectContext]; 
    } 
    return context; 
} 

要顯示我使用此代碼

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    // Configure the cell... 
    NSManagedObject *number = [self.scores objectAtIndex:indexPath.row]; 
    [cell.textLabel setText:[NSString stringWithFormat:@"Score: %@", [number valueForKey:@"score"]]]; 
} 

我使用該確切的代碼對於另一個應用程序和在表中的數據總是顯示在保存它的確切順序的細胞。我已經閱讀了很多文檔,並在使用該方法進行回答之前搜索了其他地方。我明白爲什麼信息會改變秩序。謝謝你的幫助!

回答

2

您需要設置NSFetchRequest的sortDescriptors。我無法回答爲什麼其他應用程序中的相同代碼每次都以相同的順序返回數據。我在文檔中看到的沒有任何內容說明在沒有附加排序描述符的獲取請求期間返回結果的順序。例如,如果你有一個叫做「名」屬性的實體,你會想是

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; 
+0

謝謝!我剛纔看到在我的最後一個應用程序中使用了NSSortDescriptor。 – lostAtSeaJoshua

0

有關代碼的幾個注意事項。

首先檢索排序結果,您應該使用排序描述符來對照您的樂譜屬性。

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"score" 
    ascending:YES]; 
NSArray *sortDescriptors = @[sortDescriptor]; 
[fetchRequest setSortDescriptors:sortDescriptors]; 

二,做好運行沒有通過零的錯誤,並檢查返回值的請求。

NSError *error; 
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; 
if (fetchedObjects == nil) { 
    // Handle the error. 
} 

最後,UITableView小號打交道時採取的NSFetchedResultsController優勢。

+0

謝謝!這也是一個很好的答案! – lostAtSeaJoshua

相關問題