使用Singleton管理器的CoreData

时间:2013-09-11 17:45:10

标签: ios objective-c uitableview core-data afnetworking

我想在我的应用程序中使用Singleton类实现Core Data,它将管理托管对象上下文。我没有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类在TableView中管理我的ListViewController和我的对象项目。我有单身人士。但我不太清楚我必须启动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

1 个答案:

答案 0 :(得分:0)

要重新加载表格视图,您可以将NSFetchedResultsControllerlink to Apple docs)附加到视图控制器,以便在每次更新NSManagedObjectContext时获得自动更新。由Javi Soto创建的此存储库中的代码很容易理解,以便在项目中实现NSFetchedResultsController。请查看JSBaseCoreDataTableViewController here