管理対象オブジェクト コンテキストを管理するシングルトン クラスを使用して、コア データをアプリに実装したいと考えています。すべてを管理する方法がわからないため、コアデータなしで実装しています。
今、私はこのコードを持っています:
私は自分の 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];
}
オブジェクト Project :
@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