Skip to content

Commit

Permalink
Update examples projects to reflect Core Data API changes
Browse files Browse the repository at this point in the history
  • Loading branch information
blakewatters committed Aug 7, 2012
1 parent c041c3d commit 99738db
Show file tree
Hide file tree
Showing 10 changed files with 140 additions and 91 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,5 @@

#import "RKCatalog.h"

@interface RKCoreDataExample : UITableViewController {
NSArray *_articles;
UISegmentedControl *_segmentedControl;
}

@interface RKCoreDataExample : UITableViewController
@end
58 changes: 40 additions & 18 deletions Examples/RKCatalog/Examples/RKCoreDataExample/RKCoreDataExample.m
Original file line number Diff line number Diff line change
Expand Up @@ -26,38 +26,63 @@ @implementation Article

@end

@interface RKCoreDataExample ()
@property (nonatomic, readwrite, retain) NSArray *articles;
@property (nonatomic, readwrite, retain) UISegmentedControl *segmentedControl;
@end

////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -

@implementation RKCoreDataExample

@synthesize articles = _articles;
@synthesize segmentedControl = _segmentedControl;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
RKObjectManager *manager = [RKObjectManager managerWithBaseURLString:@"http://restkit.org"];
manager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"RKCoreDataExample.sqlite"];
NSURL *baseURL = [NSURL URLWithString:@"http://restkit.org"];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:baseURL];

// Create the managed object store and add a SQLite persistent store
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
NSString *storePath = [[RKDirectory applicationDataDirectory] stringByAppendingPathComponent:@"RKCoreDataExample.sqlite"];
NSError *error;
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:nil error:&error];
NSAssert(persistentStore, @"Failed to create SQLite store at path %@ due to error: %@", storePath, error);
manager.managedObjectStore = managedObjectStore;
[managedObjectStore release];

// Once we are done with configuration, ask the store to create the primary and main queue contexts
[managedObjectStore createManagedObjectContexts];

[RKManagedObjectStore setDefaultStore:managedObjectStore];
[RKObjectManager setSharedManager:manager];

// Create some starter objects if the database is empty
if ([Article count:nil] == 0) {
NSUInteger count = [managedObjectStore.mainQueueManagedObjectContext countForEntityForName:@"Article" predicate:nil error:&error];
if (count == 0) {
for (int i = 1; i <= 5; i++) {
Article *article = [Article object];
Article *article = [managedObjectStore.mainQueueManagedObjectContext insertNewObjectForEntityForName:@"Article"];
article.articleID = [NSNumber numberWithInt:i];
article.title = [NSString stringWithFormat:@"Article %d", i];
article.body = @"This is the body";

// Persist the object store
[manager.objectStore save:nil];
}

// Persist the new objects
BOOL success = [managedObjectStore.mainQueueManagedObjectContext saveToPersistentStore:&error];
NSAssert(success, @"Failed to persist manged object context due to error: %@", error);
}

NSArray *items = [NSArray arrayWithObjects:@"All", @"Sorted", @"By Predicate", @"By ID", nil];
_segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
_segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
_segmentedControl.momentary = NO;
[_segmentedControl addTarget:self action:@selector(updateTableView) forControlEvents:UIControlEventValueChanged];
_segmentedControl.selectedSegmentIndex = 0;
self.segmentedControl = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
self.segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
self.segmentedControl.momentary = NO;
[self.segmentedControl addTarget:self action:@selector(updateTableView) forControlEvents:UIControlEventValueChanged];
self.segmentedControl.selectedSegmentIndex = 0;
}

return self;
Expand All @@ -82,14 +107,13 @@ - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger

- (NSFetchRequest *)fetchRequestForSelectedSegment
{
NSFetchRequest *fetchRequest = [Article fetchRequest];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Article"];
NSPredicate *predicate = nil;

switch (_segmentedControl.selectedSegmentIndex) {
// All objects
case 0:
// An empty fetch request will return all objects
// Duplicates the functionality of [Article allObjects]
break;

// Sorted
Expand All @@ -100,14 +124,12 @@ - (NSFetchRequest *)fetchRequestForSelectedSegment

// By Predicate
case 2:
// Duplicates functionality of calling [Article objectsWithPredicate:predicate];
predicate = [NSPredicate predicateWithFormat:@"title CONTAINS[c] %@", @"2"];
[fetchRequest setPredicate:predicate];
break;

// By ID
case 3:
// Duplicates functionality of [Article findByAttribute:@"articleID" withValue:[NSNumber numberWithInt:3]];
predicate = [NSPredicate predicateWithFormat:@"%K = %d", @"articleID", 3];
[fetchRequest setPredicate:predicate];
break;
Expand All @@ -121,9 +143,9 @@ - (NSFetchRequest *)fetchRequestForSelectedSegment

- (void)updateTableView
{
[_articles release];
NSError *error;
NSFetchRequest *fetchRequest = [self fetchRequestForSelectedSegment];
_articles = [[Article objectsWithFetchRequest:fetchRequest] retain];
self.articles = [[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext executeFetchRequest:fetchRequest error:&error];
[self.tableView reloadData];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,26 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:gRKCatalogBaseURL];
RKManagedObjectStore *objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"RKRelationshipMappingExample.sqlite"];
objectManager.objectStore = objectStore;

NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];

RKManagedObjectMapping *taskMapping = [RKManagedObjectMapping mappingForClass:[Task class] inManagedObjectStore:objectStore];
RKEntityMapping *taskMapping = [RKEntityMapping mappingForEntityForName:@"Task" inManagedObjectStore:managedObjectStore];
taskMapping.primaryKeyAttribute = @"taskID";
[taskMapping mapKeyPath:@"id" toAttribute:@"taskID"];
[taskMapping mapKeyPath:@"name" toAttribute:@"name"];
[taskMapping mapKeyPath:@"assigned_user_id" toAttribute:@"assignedUserID"];
[objectManager.mappingProvider setMapping:taskMapping forKeyPath:@"task"];

RKManagedObjectMapping *userMapping = [RKManagedObjectMapping mappingForClass:[User class] inManagedObjectStore:objectStore];
RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:@"User" inManagedObjectStore:managedObjectStore];
userMapping.primaryKeyAttribute = @"userID";
[userMapping mapAttributes:@"name", @"email", nil];
[userMapping mapKeyPath:@"id" toAttribute:@"userID"];
[userMapping mapRelationship:@"tasks" withMapping:taskMapping];
[objectManager.mappingProvider setMapping:userMapping forKeyPath:@"user"];

// Hydrate the assignedUser association via primary key
[taskMapping hasOne:@"assignedUser" withMapping:userMapping];
[taskMapping connectRelationship:@"assignedUser" withObjectForPrimaryKeyAttribute:@"assignedUserID"];
[taskMapping connectRelationship:@"assignedUser" withMapping:userMapping fromKeyPath:@"assignedUserID" toKeyPath:@"userID"];

// NOTE - Project is not backed by Core Data
RKObjectMapping *projectMapping = [RKObjectMapping mappingForClass:[Project class]];
Expand All @@ -48,6 +48,20 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
[projectMapping mapRelationship:@"user" withMapping:userMapping];
[projectMapping mapRelationship:@"tasks" withMapping:taskMapping];
[objectManager.mappingProvider setMapping:projectMapping forKeyPath:@"project"];

// Complete Core Data initialization
NSError *error;
NSString *storePath = [[RKDirectory applicationDataDirectory] stringByAppendingPathComponent:@"RKRelationshipMappingExample.sqlite"];
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:nil error:&error];
NSAssert(persistentStore, @"Failed to create persistent store with error: %@", error);
[managedObjectStore createManagedObjectContexts];

// Create a managed object cache. To use the In Memory Cache, you must configure it after context creation
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.primaryManagedObjectContext];

// TODO: Need to update setPrimaryKeyAttributeName to use info dictionary...
objectManager.managedObjectStore = managedObjectStore;
[managedObjectStore release];
}

return self;
Expand Down Expand Up @@ -76,7 +90,10 @@ - (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)ob

- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Rats!" otherButtonTitles:nil];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Rats!" otherButtonTitles:nil];
[alert show];
[alert release];
}
Expand Down Expand Up @@ -151,13 +168,11 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N
}

if (indexPath.section == 0) {
Project *project = (Project *)[_objects objectAtIndex:indexPath.row];
Project *project = [_objects objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = project.name;
} else if (indexPath.section == 1) {
// NOTE: We refetch the object here because Project is not Core Data backed
NSManagedObject *objectReference = [_selectedProject.tasks objectAtIndex:indexPath.row];
Task *task = (Task *)[[RKObjectManager sharedManager].objectStore objectWithID:[objectReference objectID]];
Task *task = [_selectedProject.tasks objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@", task.name];
cell.detailTextLabel.text = [NSString stringWithFormat:@"Assigned to: %@", task.assignedUser.name];
}
Expand Down
4 changes: 3 additions & 1 deletion Examples/RKCatalog/RKCatalog.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@
2501DE4F13607B67003DE9E4 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0420;
LastUpgradeCheck = 0450;
ORGANIZATIONNAME = "Two Toasters";
};
buildConfigurationList = 2501DE5213607B67003DE9E4 /* Build configuration list for PBXProject "RKCatalog" */;
Expand Down Expand Up @@ -569,6 +569,7 @@
GCC_DYNAMIC_NO_PIC = NO;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "App/RKCatalog-Prefix.pch";
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
HEADER_SEARCH_PATHS = "\"$(BUILT_PRODUCTS_DIR)/../../Headers\"";
INFOPLIST_FILE = "App/RKCatalog-Info.plist";
LIBRARY_SEARCH_PATHS = "\"$(SRCROOT)\"";
Expand All @@ -585,6 +586,7 @@
COPY_PHASE_STRIP = YES;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "App/RKCatalog-Prefix.pch";
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
HEADER_SEARCH_PATHS = "\"$(BUILT_PRODUCTS_DIR)/../../Headers\"";
INFOPLIST_FILE = "App/RKCatalog-Info.plist";
LIBRARY_SEARCH_PATHS = "\"$(SRCROOT)\"";
Expand Down
4 changes: 3 additions & 1 deletion Examples/RKMacOSX/RKMacOSX.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@
25D6390B135184CE000879B1 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0430;
LastUpgradeCheck = 0450;
};
buildConfigurationList = 25D6390E135184CE000879B1 /* Build configuration list for PBXProject "RKMacOSX" */;
compatibilityVersion = "Xcode 3.2";
Expand Down Expand Up @@ -372,6 +372,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
Expand All @@ -393,6 +394,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
Expand Down
3 changes: 2 additions & 1 deletion Examples/RKTwitter/Classes/RKTwitterAppDelegate.m
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(
RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);

// Initialize RestKit
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURLString:@"http://twitter.com"];
NSURL *baseURL = [NSURL URLWithString:@"http://twitter.com"];
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:baseURL];

// Enable automatic network activity indicator management
objectManager.client.requestQueue.showsNetworkActivityIndicatorWhenBusy = YES;
Expand Down
Loading

0 comments on commit 99738db

Please sign in to comment.