在IOS中获取核心数据

时间:2015-03-24 18:00:18

标签: ios objective-c core-data

我是CoreData的新手,我正在阅读一些教程。

这是我的数据模型:

Data model

我希望建立类似于现场比分的东西。所以我添加了一些遵循这种格式的演示数据:

// -------------------------------------------------------------------------
// --   GW :    1                                           2
//              |                                           |
//          Premier League                               Primera
//         /            \                                   |
//  Chelsea vs M.City  Arsenal vs Liverpool      Real Mad vs Barcelona
// -------------------------------------------------------------------------

我可以验证它们已保存,您可以从以下屏幕截图中看到:

Table 1

Table 2

所以,现在我需要的是将这些数据提取到我的应用程序中。我添加了这些调试功能:

# pragma -
# pragma  mark - different fetch functions

- (void) fetchGameweeksAndLeagues {
    /*
     Set up the fetched results controller.
     */
    NSLog(@"Fetch Gameweeks and Leagues");
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entityGW = [NSEntityDescription entityForName:@"GameWeek" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entityGW];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    NSError *fetchError = nil;
    NSArray *result = [self.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];

    if (!fetchError) {
        for (NSManagedObject *managedObject in result) {
            NSLog(@"GwId:%@, League: %@", [managedObject valueForKey:@"gwId"], [[managedObject valueForKey:@"leagues"] valueForKey:@"leagueName"]/*,[[managedObject valueForKey:@"matches"] valueForKey:@"homeTeam"],[[managedObject valueForKey:@"matches"] valueForKey:@"awayTeam"]*/);
        }

    } else {
        NSLog(@"Error fetching data.");
        NSLog(@"%@, %@", fetchError, fetchError.localizedDescription);
    }
}

-(void) fetchMatchesForLeagueWithId/*:(NSNumber*)leagueId*/
{
    NSLog(@"Fetch Matches for specific League");
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entityLeague = [NSEntityDescription entityForName:@"League" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entityLeague];


    NSError *fetchError = nil;
    NSArray *result = [self.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];

    if (!fetchError) {
        for (NSManagedObject *managedObject in result) {
            NSLog(@"League: %@, Teams : %@ vs %@", [managedObject valueForKey:@"leagueName"],[[managedObject valueForKey:@"matches"] valueForKey:@"homeTeam"],[[managedObject valueForKey:@"matches"] valueForKey:@"awayTeam"]);
        }
    } else {
        NSLog(@"Error fetching data.");
        NSLog(@"%@, %@", fetchError, fetchError.localizedDescription);
    }
}

所以,我的输出是:

2015-03-24 17:38:42.236 SofaRef[73743:2215371] GwId:1, League: {(
    "Premier League"
)}
2015-03-24 17:38:42.236 SofaRef[73743:2215371] GwId:2, League: {(
    Primera
)}
2015-03-24 17:38:42.236 SofaRef[73743:2215371] Fetch Matches for specific League
2015-03-24 17:38:42.237 SofaRef[73743:2215371] League: Primera, Teams : {(
    "Real Madrid"
)} vs {(
    Barcelona
)}
2015-03-24 17:38:42.237 SofaRef[73743:2215371] League: Premier League, Teams : {(
    Chelsea,
    Arsenal
)} vs {(
    Liverpool,
    "Man.City"
)}

那么,我如何以正确的顺序打印它们呢?

我想以与DB相同的顺序打印它们。这意味着打印切尔西队对阵Man.City和阿森纳队对阵利物浦而不是“分组”栏目 - 我想将他们作为“排”进行打击。

2 个答案:

答案 0 :(得分:1)

因为从League到Match的关系是一对多关系,matches的{​​{1}}属性返回NSSet,即League是NSSet。在NSLog语句中,使用:

[managedObject valueForKey:@"matches"]

这将获取上述NSSet的每个元素,获取[[managedObject valueForKey:@"matches"] valueForKey:@"homeTeam"] 属性值,并将结果作为新的NSSet返回。记录此NSSet时,它会列出所有值:

homeTeam

但由于NSSet 无序,结果可能是任何顺序。实际上,正如您的结果所示,价值

{(
    Chelsea,
    Arsenal
)}

的顺序相反:

[[managedObject valueForKey:@"matches"] valueForKey:@"awayTeam"]

您需要做的是分别记录每个{( Liverpool, "Man.City" )} ,每个matchhomeTeam。您可以通过嵌套另一个for循环来完成此操作:

awayTeam

这将确保您的输出显示在“行”而不是“列”中。但它仍然以随机顺序呈现匹配,这可能与SQL数据库中的序列匹配,也可能不匹配。通常,您不应假设数据库中的条目具有任何特定顺序。如果顺序很重要,则应在从数据库中获取值时指定它(或者在获取数据后对其进行排序)。要实现此目的,请使用 for (NSManagedObject *managedObject in result) { NSLog(@"League: %@", [managedObject valueForKey:@"leagueName"]); for (NSManagedObject *match in [managedObject valueForKey:@"matches"]) { NSLog(@"Teams : %@ vs %@", [match valueForKey:@"homeTeam"],[match valueForKey:@"awayTeam"]); } } 。假设您的偏好是匹配按字母顺序排列NSSortDescriptor;使用以下sortDescriptor:

homeTeam

您要排序的集合是NSSortDescriptor *homeTeamSort = [NSSortDescriptor sortDescriptorWithKey:@"homeTeam" ascending:YES]; 关系,因此修改上面的代码如下:

matches

答案 1 :(得分:0)

//核心数据演示

import UIKit
import CoreData

class ViewController: UIViewController

{
@IBOutlet var txt_add: UITextField!
@IBOutlet var txt_name: UITextField!
let contex = ((UIApplication.shared.delegate) as! AppDelegate).persistentContainer.viewContext;
override func viewDidLoad()
{
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
@IBAction func btn_insert(_ sender: UIButton)
{
    let entity = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: contex);
    entity.setValue(txt_name.text, forKey: "empname");
    entity.setValue(txt_add.text, forKey: "empadd");
    do
    {
        try contex.save();
    }
    catch
    {

    }
}
@IBAction func btn_select(_ sender: UIButton)
{
    let entitydic = NSEntityDescription.entity(forEntityName: "Employee", in: contex);
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Employee")
    request.entity = entitydic;
    let pred = NSPredicate(format: "(empname = @%)", txt_name.text!);
    request.predicate = pred;
    do
    {
        let arr = try contex.fetch(request);
        if arr.count > 0
        {
            let obj = arr[0] as! NSManagedObject;
            txt_name.text = obj.value(forKey: "empname") as? String;
            txt_add.text = obj.value(forKey: "empadd") as? String;
        }
    }
    catch
    {

    }
}
@IBAction func btn_update(_ sender: UIButton)
{
    let entitydic = NSEntityDescription.entity(forEntityName: "Employee", in: contex);
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Employee")
    request.entity = entitydic;
    let pred = NSPredicate(format: "(empname = %@)", txt_name.text!);
    request.predicate = pred;

    do
    {
        let arr = try contex.fetch(request);
        if arr.count > 0
        {
            let obj = arr[0] as! NSManagedObject;
            obj.setValue(txt_name.text, forKey: "empname");
            obj.setValue(txt_add.text, forKey: "empadd");

            do
            {
                try  contex.save();
            }
            catch
            {

            }
        }
    }
    catch
    {

    }

}

@IBAction func btn_delete(_ sender: UIButton)
{
    let entitydic = NSEntityDescription.entity(forEntityName: "Employee", in: contex);
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Employee");
    request.entity = entitydic;
    let pred = NSPredicate(format:"(empname = %@)", txt_name.text!);
    request.predicate = pred;
    do
    {
        let arr = try contex.fetch(request);
        if arr.count > 0
        {
            let obj = arr[0] as! NSManagedObject;
            contex.delete(obj)

            do
            {
                try contex.save();
            }
            catch
            {

            }
        }
    }
    catch
    {

    }
}
override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}