0

我想在我的应用程序中使用将管理托管对象上下文的单例类来实现核心数据。我有没有 Core Data 的实现,因为我不知道如何管理所有内容。

现在,我有这个代码:

我有我的 ListViewController:

@interface YPProjectListViewController () {
    SelectionSuccessBlock2 successBlock;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray * data;
@property (nonatomic, strong) UIRefreshControl *spinner ;
@end

@implementation YPProjectListViewController

@synthesize tableView;
@synthesize data;
@synthesize spinner;

- (void)viewDidLoad {
    [super viewDidLoad];
    spinner = [[UIRefreshControl alloc]initWithFrame:CGRectMake(130, 10, 40, 40)];
    [self loadProjectsFromService];
    [spinner addTarget:self action:@selector(loadProjectsFromService) forControlEvents:UIControlEventValueChanged];
    [tableView addSubview:spinner];


    }


-(void)loadProjectsFromService{
     [spinner beginRefreshing];
    self.data = [[NSMutableArray alloc] init];
     [self.tableView reloadData];
    [self.view addSubview:self.tableView];
    __weak typeof(self) weakSelf = self;
    successBlock = ^(NSMutableArray *newData) {
        if ([newData count] > 0) {
            [weakSelf refreshData:newData];
        }

    };
        [spinner endRefreshing];
    [ypNetManager getProjectListWithSuccessBlock:successBlock error:NULL];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Custom getter

- (UITableView *)tableView {
    //custom init of the tableview
    if (!tableView) {
        // regular table view
        tableView = [[UITableView alloc] initWithFrame:UIEdgeInsetsInsetRect(self.view.bounds, tableViewInsets) style:UITableViewStylePlain];
        tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor clearColor];
        return tableView;
    }
    return tableView;
}

#pragma mark - Private methods 

- (void)refreshData:(NSMutableArray *)newData {

    self.data = newData;
    [self.tableView reloadData];
}

我的方法有我的 AFNetworking AFHttpClient 子类:

- (void)getProjectListWithSuccessBlock:(SelectionSuccessBlock2)success error:(SelectionErrorBlock)error {
    NSMutableURLRequest *request = [self requestWithMethod:@"GET" path:kAPIProjectListDev parameters:nil];
    [request setTimeoutInterval:kTimeOutRequest];

    AFJSONRequestOperation *requestOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//            NSLog(@"%@ Susscess JSNON Response: %@", NSStringFromSelector(_cmd),JSON);
            NSMutableArray * data = [[NSMutableArray alloc] init];

            NSDictionary *projects = [JSON valueForKey:kTagProjects];
            for (NSDictionary *projectDic in projects) {
                [data addObject:[Project createProjectWithDictionary:projectDic]];
            }
            if (success) {
                success(data);
            }
        }
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *aError, id JSON) {
           NSLog(@"%@ Failure JSNON Error%@", NSStringFromSelector(_cmd), aError);
           if (error) {
               error(aError);
            }
        }];

    [self enqueueHTTPRequestOperation:requestOperation];
}

对象项目:

@property (nonatomic, strong) NSNumber *projectId;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSNumber *estimatedPrice;

及其类别助手:

@implementation Project (Helper)
+ (Project *)createProjectWithDictionary:(NSDictionary *)dic {
    Project *project = [[Project alloc] init];
    project.projectId = [NSNumber numberWithInt:[[dic valueForKey:kTagProjectId] intValue]];
    project.title = [dic valueForKey:kTagProjectTitle];
    project.estimatedPrice = [NSNumber numberWithInt:[[dic valueForKey:kTagProjectEstimatedPrice] floatValue]];
    //    NSLog(@"Project ..... %d, Title: %@", [project.projectId intValue], project.title);
    return project;
}
@end

现在,我想使用我的 DataSingleton 类来管理我的 ListViewController 和我在 TableView 中的对象项目。我有单身人士。但我不太明白我必须在哪里启动 managedObjectContext。或者我必须重新加载 TableView ..

//
//  DataSingleton.m
//  Yeeplys
//
//  Created by Carlos Roig Salvador on 8/31/13.
//  Copyright (c) 2013 Carlos Roig Salvador. All rights reserved.
//

#import "DataSingleton.h"


//static instance for singleton implementation
static DataSingleton __strong *manager = nil;

//Private instance methods/properties
@interface DataSingleton()

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and
// bound to the persistent store coordinator for the application.
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's
// store added to it.
@property (readonly,strong,nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory;
@end


@implementation DataSingleton

@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;

//DataAccessLayer singleton instance shared across application
+ (id)sharedInstance
{
    @synchronized(self)
    {
        if (manager == nil)
            manager = [[self alloc] init];
    }
    return manager;
}

+ (void)disposeInstance
{
    @synchronized(self)
    {
        manager = nil;
    }
}

+(NSManagedObjectContext *)context
{
    return [[DataSingleton sharedInstance] managedObjectContext];
}

//Saves the Data Model onto the DB
- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            //Need to come up with a better error management here.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and
// bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
        return __managedObjectContext;

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the
// application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
        return __managedObjectModel;

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"yeeplyModel"
                                              withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc]
                            initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the
// application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
        return __persistentStoreCoordinator;

    NSURL *storeURL = [[self applicationDocumentsDirectory]
                       URLByAppendingPathComponent:@"MyData.sqlite"];

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
                                    initWithManagedObjectModel:[self managedObjectModel]];

    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                                    configuration:nil URL:storeURL options:nil error:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return __persistentStoreCoordinator;
}

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                                   inDomains:NSUserDomainMask] lastObject];
}

@end
4

1 回答 1

0

要重新加载您的表格视图,您可以将一个NSFetchedResultsController指向 Apple 文档的链接)附加到您的视图控制器,以便在每次更新您的NSManagedObjectContext. 这个存储库中有一个由 Javi Soto 编写的代码,易于理解,以便NSFetchedResultsController在您的项目中实现。看看JSBaseCoreDataTableViewController 这里

于 2014-02-04T13:56:44.290 回答