Restkit 0.20 pre4 core data issue - core-data

{"status":"ok",
"count":5,
"count_total":165,
"pages":33,
"posts":[{ "id":2971,
"status":"publish",
"title":"title1",
"content":"",
"date":"date",
"categories":[{"id":5,
"title":"category1"},
{"id":7,
"title":"category2"}],
"thumbnail":"url",
"custom_fields":{"wpcf-content":["content"],
"wpcf-audio":["url"]}
},
{ "id":2974,
"status":"publish",
"title":"title2",
"content":"",
"date":"date2",
"categories":[{"id":5,
"title":"category1"},
{"id":5,
"title":"category3"}
],
"thumbnail":"url",
"custom_fields":{"wpcf-content":["content"],
"wpcf-audio":["url"]}
}
]
}
posts.h
#interface posts : NSManagedObject
#property (nonatomic, retain) NSString* title;
#property (nonatomic, retain) NSArray* wpcf-content;
#property (nonatomic, retain) NSArray* wpcf-audio;
#property (nonatomic, retain) NSString* id;
#property (nonatomic, retain) NSArray* categories;
#end
categories.h
#interface categories : NSManagedObject
#property (nonatomic, retain) NSString* title;
#end
Model.xcdatamodeld
entities Posts : title (string), id (integer 64),wpcf-audio (transformable),wpcf-content (transformable)
Categories : title (string)
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:#"Model.sqlite"];
[managedObjectStore addSQLitePersistentStoreAtPath:path fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:nil];
[managedObjectStore createManagedObjectContexts];
RKEntityMapping *categoryMapping = [RKEntityMapping mappingForEntityForName:#"Categories" inManagedObjectStore:managedObjectStore];
[categoryMapping addAttributeMappingsFromDictionary:#{ #"title":#"title"}];
RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:#"Posts" inManagedObjectStore:managedObjectStore];
NSArray *identification =[[NSArray alloc]initWithObjects:#"id", nil];
mapping.identificationAttributes= identification;
[mapping addAttributeMappingsFromArray:#[#"title",#"id",#"custom_fields.wpcf-content",#"custom_fields.wpcf-audio"]];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // Anything in 2xx
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping pathPattern:nil keyPath:#"posts" statusCodes:statusCodes];
[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"categories" toKeyPath:#"categories" withMapping:categoryMapping]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://my.url/json"]];
RKManagedObjectRequestOperation *operation = [[RKManagedObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[responseDescriptor]];
operation.managedObjectContext = managedObjectStore.mainQueueManagedObjectContext;
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
posts *article = [result firstObject];
categories *catego =[article.categories objectAtIndex:0];
NSLog(#"Mapped the article: %#", article.title);
NSLog(#"Mapped the article: %#", catego.title);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Failed with error: %#", [error localizedDescription]);
}];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"http://my.url/"]];
[manager enqueueObjectRequestOperation:operation];
I get this error W restkit.core_data:RKManagedObjectMappingOperationDataSource.m:157 Performing managed object mapping with a nil managed object cache:
Unable to update existing object instances by identification attributes. Duplicate objects may be created.

Related

bool value does NOT get stored in core data stack

I'm trying to simply toggle a BOOL Attribute in my core data stack and also use that coredata bool to set the "state" of a UISwitch in viewDidLoad in my mainView.
following scenario:
Switch is off, user hits edit(save) UIButton, --> that toggles the settingSysTimeOverride Attribute of entity Setting from #NO to #YES
next time app launches, in viewDidLoad, I fetch the core data stack and look at status of settingSysTimeOverride and use that to
set the "state" of my UISwitch.
But for some reason, my value does NOT get stored to core data stack.
The whole project is attached, also here is my code.
MainViewController.m
#import "MainViewController.h"
#import "AppDelegate.h"
#interface MainViewController ()
#property (nonatomic, strong)NSManagedObjectContext *managedObjectContext;
#property (nonatomic, strong)NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) NSMutableArray *settingsArray;
#end
#implementation MainViewController
#synthesize editSetting;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (NSManagedObjectContext *)managedObjectContext
{
return [(AppDelegate*)[[UIApplication sharedApplication]delegate]managedObjectContext];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Setting" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"settingSysTimeOverride == %#", editSetting];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
NSLog(#"ERROR! %# - %#", [error localizedDescription], [error userInfo]);
} else {
NSLog(#"FETCH SUCCESSFUL");
}
if ((fetchedObjects.count) >0) {
// list array contents
for (int i=0; i < (fetchedObjects.count); i++) {
// output for debug purpose
NSLog(#"Array-index [%i]: %#", i, fetchedObjects[i]);
}
}
// check settingSysTimeOverride and set UISwitch-State
if (editSetting.settingSysTimeOverride.boolValue == 0) {
// turn switch to OFF - Position
_overrideSysTimeSwitch.on = NO;
} else {
// turn switch to ON - Position
_overrideSysTimeSwitch.on = YES;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)editSave:(UIBarButtonItem *)sender
{
// toggle BOOL status of settingSysTimeOverride here
//
}
- (IBAction)overrideSysTime:(UISwitch *)sender
{
}
- (IBAction)timeFormat:(UISwitch *)sender {
}
#end
MainViewController.h
#import <UIKit/UIKit.h>
#import "Setting.h"
#interface MainViewController : UIViewController <NSFetchedResultsControllerDelegate>
#property (nonatomic, strong)Setting *editSetting;
#property (strong, nonatomic) IBOutlet UIBarButtonItem *editSaveButton
#property (strong, nonatomic) IBOutlet UILabel *overrideSysTimeLabel;
#property (strong, nonatomic) IBOutlet UILabel *timeFormatLabel;
#property (strong, nonatomic) IBOutlet UISwitch *overrideSysTimeSwitch;
#property (strong, nonatomic) IBOutlet UISwitch *timeFormatSwitch;
- (IBAction)editSave:(UIBarButtonItem *)sender;
- (IBAction)overrideSysTime:(UISwitch *)sender;
- (IBAction)timeFormat:(UISwitch *)sender;
#end
AppDelegate.h
#import <UIKit/UIKit.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
Setting.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface Setting : NSManagedObject
#property (nonatomic, retain) NSString * settingName;
#property (nonatomic, retain) NSNumber * settingSysTimeOverride;
#property (nonatomic, retain) NSNumber * settingTimeFormat;
#end
Setting.m
#import "Setting.h"
#implementation Setting
#dynamic settingName;
#dynamic settingSysTimeOverride;
#dynamic settingTimeFormat;
#end
Can someone please help me with this???
here is what I was doing wrong, I hope it's going to help others in the future to avoid running in the same issues:
I forgot to point my NSManagedObject at the beginning of my fetched array.
NSManagedObject *matches;
matches=[objects objectAtIndex:(0)];
The code in one piece would look like this:
NSManagedObjectContext *context;
NSEntityDescription *entityDesc;
NSFetchRequest *request;
NSPredicate *pred;
NSManagedObject *matches;
NSArray *objects;
NSUInteger elementsInArray;
context = [self managedObjectContext];
entityDesc = [NSEntityDescription entityForName:#"Setting" inManagedObjectContext:context];
pred = [NSPredicate predicateWithFormat:#"(settingName = %#)", #"User-Settings"];
request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
[request setPredicate:pred];
matches = nil;
NSError *errorFS = nil;
if (!(objects = [context executeFetchRequest:request error:&errorFS])) {
// fetch failed
NSLog(#"Fetch failed: %# - %#", [errorFS localizedDescription], [errorFS userInfo]);
} else {
// fetch succeeded
NSLog(#"Fetch Succeeded");
}
if ([objects count] == 0)
{ // does not exist -> error?
} else
{
matches=[objects objectAtIndex:(0)]; // <- HERE WAS THE ERROR !!!!!
// # system time override switch
if([[matches valueForKey:#"settingSysTimeOverride"] boolValue]) {
_sysTimeOverrideSwitch.on = YES;
} else {
_sysTimeOverrideSwitch.on = NO;
}
}

CoreData: Error by decode data from Context/Store NSData -> NSArray

i'm new in iOS-Development area and trying now to update an existing App to iOS 6.1 from iOS4.
get Data from Store to show in NewsPageView : UIViewController
NewsPageView.m
#import "NewsPageView.h"
#interface NewsPageView ()
#end
#implementation NewsPageView
#synthesize newsDetailsView,
newsTableView,
newsHeaderText
;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
/*
* Get managedObjectContext and List of News over AppDelegate
*/
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
//Setting self.managedObjectContext
self.managedObjectContext = appDelegate.managedObjectContext;
// Fetching Records from the data base to show in the table
self.listOfNews = [[appDelegate getDataFromStore:self]copy];
//
NSLog(#"Data from Store in NewsPageView: %#",self.listOfNews.description);
}
try to set/write data into Context
-(void) setDataToStore
{
NSLog(#"Trying to write News in Store");
News *newNews = [NSEntityDescription insertNewObjectForEntityForName:#"News" inManagedObjectContext:self.managedObjectContext];
newNews.newsId = [[NSNumber alloc]initWithInt:508];
newNews.title = #"Some Title";
newNews.content = #"Some content";
newNews.detailsUrl = #"www.someURL.de";
newNews.date = [[NSDate alloc]init];
newNews.dateTs = [[NSNumber alloc]initWithInt:138114787];
newNews.primaryCat = [[NSNumber alloc]initWithInt:0];
//make Categorien...
NewsCategorien *cat1 = [NSEntityDescription insertNewObjectForEntityForName:#"NewsCategorien" inManagedObjectContext:self.managedObjectContext];
cat1.catId = [[NSNumber alloc]initWithInt:1];
cat1.name = #"Windows";
cat1.news = newNews;
NewsCategorien *cat2 = [NSEntityDescription insertNewObjectForEntityForName:#"NewsCategorien" inManagedObjectContext:self.managedObjectContext];
cat2.catId = [[NSNumber alloc]initWithInt:2];
cat2.name = #"Linux";
cat2.news = newNews;
NewsCategorien *cat3 = [NSEntityDescription insertNewObjectForEntityForName:#"NewsCategorien" inManagedObjectContext:self.managedObjectContext];
cat3.catId = [[NSNumber alloc]initWithInt:3];
cat3.name = #"Apple";
cat3.news = newNews;
NewsCategorien *cat5 = [NSEntityDescription insertNewObjectForEntityForName:#"NewsCategorien" inManagedObjectContext:self.managedObjectContext];
cat5.catId = [[NSNumber alloc]initWithInt:5];
cat5.name = #"Smartphone";
cat5.news = newNews;
newNews.isNews = [NSNumber numberWithBool:YES];
NSArray *catListe = [NSArray arrayWithObjects:cat1,cat2,cat3,cat5, nil];
// //saving cat by converting Cat. objects
// newNews.categories = catListe;
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
NSLog(#"Saving ok!");
}
try to get Data from Context
- (NSArray *)getDataFromStore:(id)sender
{
// initializing NSFetchRequest
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSArray *fetchedData;
//get Data für NewsTable View
if([sender isKindOfClass:[NewsPageView class]]){
//Setting Entity to be Queried
fetchRequest.entity = [NSEntityDescription entityForName:#"News" inManagedObjectContext:self.managedObjectContext];
NSError* error;
//Point of Error by debugging!!!
//return list of News
fetchedData = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
}
//print fetched Data
for (News *news in fetchedData) {
NSLog(#"News:%#", news.description);
}
// Returning Fetched News
return fetchedData;
}
Classes
News.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class NewsCategorien;
#interface News : NSManagedObject <NSCoding>
#property (nonatomic, retain) id categories;
#property (nonatomic, retain) NSString * content;
#property (nonatomic, retain) NSDate * date;
#property (nonatomic, retain) NSNumber * dateTs;
#property (nonatomic, retain) NSString * detailsUrl;
#property (nonatomic, retain) NSNumber * isNews;
#property (nonatomic, retain) NSNumber * newsId;
#property (nonatomic, retain) NSNumber * primaryCat;
#property (nonatomic, retain) NSString * title;
#property (nonatomic, retain) NSSet *categorie;
//have to be implement...
//to work with NSKeyedArchiver by serialising Objects
- (void)encodeWithCoder:(NSCoder *)aCoder;
//to work with NSKeyedUnarchiver by deserialising Objects
- (id)initWithCoder:(NSCoder *)aDecoder;
#end
#interface News (CoreDataGeneratedAccessors)
- (void)addCategorieObject:(NewsCategorien *)value;
- (void)removeCategorieObject:(NewsCategorien *)value;
- (void)addCategorie:(NSSet *)values;
- (void)removeCategorie:(NSSet *)values;
#end
/*
* News Transformer NSArray -> NSData and reverse
* Model: News should have Attribut type of Transformable and have name NewsTrasformer
*/
#interface NewsTransformer : NSValueTransformer
#end
News.m
#import "News.h"
#import "NewsCategorien.h"
#implementation News
#dynamic categories;
#dynamic content;
#dynamic date;
#dynamic dateTs;
#dynamic detailsUrl;
#dynamic isNews;
#dynamic newsId;
#dynamic primaryCat;
#dynamic title;
#dynamic categorie;
//tell the archiver how to transform the serialized representation into a new object -> deserialize Objects!
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
self.categories = [decoder decodeObjectForKey:#"categories"];
self.content = [decoder decodeObjectForKey:#"content"];
self.date = [decoder decodeObjectForKey:#"date"];
self.dateTs = [decoder decodeObjectForKey:#"dateTs"];
self.detailsUrl = [decoder decodeObjectForKey:#"detailsUrl"];
self.isNews = [decoder decodeObjectForKey:#"isNews"];
self.newsId = [decoder decodeObjectForKey:#"newsId"];
self.primaryCat = [decoder decodeObjectForKey:#"primaryCat"];
self.title = [decoder decodeObjectForKey:#"title"];
self.categorie = [decoder decodeObjectForKey:#"categorie"];
}
NSLog(#"<<<< ---- Deserialize Object News (Init With Code) --->");
return self;
}
//tell the archiver how to serialize your object into bytes -> serialize Objects!
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.categories forKey:#"categories"];
[encoder encodeObject:self.content forKey:#"content"];
[encoder encodeObject:self.date forKey:#"date"];
[encoder encodeObject:self.dateTs forKey:#"dateTs"];
[encoder encodeObject:self.detailsUrl forKey:#"detailsUrl"];
[encoder encodeObject:self.isNews forKey:#"isNews"];
[encoder encodeObject:self.newsId forKey:#"newsId"];
[encoder encodeObject:self.primaryCat forKey:#"primaryCat"];
[encoder encodeObject:self.title forKey:#"title"];
[encoder encodeObject:self.categorie forKey:#"categorie"];
NSLog(#"<<<< ---- Serialize Object News (encode With Coder) --->");
}
#end
//
#implementation NewsTransformer
//Return the Class for Forwarding Transformation
+ (Class)transformedValueClass
{
return [NSArray class];
}
+ (BOOL)allowsReverseTransformation
{
return YES;
}
// converts the NSArray into NSData using NSKeyedArchiver
- (id)transformedValue:(id)value
{
NSLog(#"Transformer: NSArray -> NSData");
return [NSKeyedArchiver archivedDataWithRootObject:value];
}
// by default raises an exception if +allowsReverseTransformation returns NO and otherwise invokes transformedValue:
//converts NSData to an NSArray using NSKeyedUnarchiver
- (id)reverseTransformedValue:(id)value
{
NSLog(#"Transformer: NSData -> NSArray");
return [NSKeyedUnarchiver unarchiveObjectWithData:value];
}
#end
NewsCategorien.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class News;
#interface NewsCategorien : NSManagedObject <NSCoding>
#property (nonatomic, retain) NSNumber * catId;
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) News *news;
//for serializing of objects have to be implement...
- (void)encodeWithCoder:(NSCoder *)aCoder;
//for serializing of objects have to be implement...
- (id)initWithCoder:(NSCoder *)aDecoder;
#end
NewsCategorien.m
#import "NewsCategorien.h"
#import "News.h"
#implementation NewsCategorien
#dynamic catId;
#dynamic name;
#dynamic news;
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
self.catId = [decoder decodeObjectForKey:#"catId"];
self.name = [decoder decodeObjectForKey:#"name"];
self.news = [decoder decodeObjectForKey:#"news"];
}
NSLog(#"<<<< ---- Deserialize Object Categorie ---> : %#",self.description);
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.catId forKey:#"catId"];
[encoder encodeObject:self.name forKey:#"name"];
[encoder encodeObject:self.news forKey:#"news"];
NSLog(#"<<<< ---- Serialize Object Categorie ---> %#",self.description);
}
#end
Model
News
Attribute: categorien Type: Transformable Name: NewsTransformer
Relationchip one-to-more
categorien Des. NewsCategorien Inverse news
Categorien
Att. catId String
Att. name Interger16
My problem:
1. writing data to the context - OK
2.when i'm trying to get data from the context(NSData->NSArray) i get following error:
Error
CoreData: error: Failed to call designated initializer on NSManagedObject class 'NewsCategorien'
2013-11-20 16:03:19.204 securityNews[19458:c07] -[NewsCategorien setCatId:]: unrecognized selector sent to instance 0x8173740
2013-11-20 16:03:19.205 securityNews[19458:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NewsCategorien setCatId:]: unrecognized selector sent to instance 0x8173740'
any idea what i doing wrong??
The first error is almost certainly due to your implementation of initWithCoder:, specifically this line:
if (self = [super init]) {
You can't create a managed object using init. You must use the designated initializer initWithEntity:insertIntoManagedObjectContext:. Or you can use NSEntityDescription's method insertNewObjectForEntityForName:inManagedObjectContext:. But using init is right out, and doing so will cause a Failed to call designated initializer error.
This means that your initWithCoder needs to be able to find a managed object context. How you do that depends on your app's structure and where you are creating contexts. If your app delegate has a context object and that's the one you want to use, you could look it up from there. If it's some other context, you'll have to get it from somewhere else. You have a couple of versions of initWithCoder and they both have this problem.
The second error is a side-effect of the first error. In initWithCoder you do this:
if (self = [super init]) {
self.catId = [decoder decodeObjectForKey:#"catId"];
....
But since [super init] doesn't work, you're getting back a bogus object that doesn't know what catId is. Then you try to set catId and it fails. Fix the first error and the second error will disappear.

CoreData: error: Failed to call designated initializer on NSManagedObject class 'Class Name'

I was trying to use CoreData along with RestKit 0.20.0 i got CoreData error.
// Response.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface Response : NSManagedObject
#property (nonatomic, retain) NSString * status;
#property (nonatomic, retain) NSString * responseCode;
#property (nonatomic, retain) NSString * responseMsg;
#property (nonatomic, retain) NSString * error;
#property (nonatomic, retain) NSString * statisticsDetails;
#end
and Implementaion file is
// Response.m
import "Response.h"
#implementation Response
#dynamic error;
#dynamic responseCode;
#dynamic responseMsg;
#dynamic statisticsDetails;
#dynamic status;
#end
and my ViewController code is
// ViewController.m
#import "ViewController.h"
#import "StatisticsDetails.h"
#import "TopProjects.h"
#import <RestKit.h>
- (void)viewDidLoad
{
[super viewDidLoad];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"http://mylocalUrl.com/Port"]];
/*managed object model */
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Model" withExtension:#"momd"];
NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
NSLog(#"managed object model: %#", managedObjectModel);
/* managed object store */
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
manager.managedObjectStore = managedObjectStore;
NSLog(#"managed object store: %#", managedObjectStore);
/* persistent store*/
NSError *error;
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:#"Model.sqlite"];
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];
if (error) {
NSLog(#"unresolved error , ");
NSAssert(persistentStore, #"Failed to add persistent store with error: %#", error);
}
/* managed object contexts*/
[managedObjectStore createManagedObjectContexts];
/* entity mapping */
RKEntityMapping *responseEntityMapping =[RKEntityMapping mappingForEntityForName:#"Response" inManagedObjectStore:managedObjectStore];
[responseEntityMapping addAttributeMappingsFromDictionary:#{
#"status" : #"status",
#"responseCode":#"responseCode",
#"responseMsg":#"responseMsg",
#"error":#"error",
#"statisticsDetails":#"statisticsDetails"
}];
RKResponseDescriptor *ResponseDescriptor = [ RKResponseDescriptor responseDescriptorWithMapping:responseEntityMapping pathPattern:nil keyPath:#"" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] getObjectsAtPath:#"getStatistics/4" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
/* NSLog(#"mapping result: %d", [mappingResult array].count);
NSLog(#"Mapping Result: %#", mappingResult.array);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
}];
Error is
2013-07-12 12:35:09.098 Dashboard[85919:5403] CoreData: error: Failed to call designated initializer on NSManagedObject class 'ResponseClas'
Please help me. Thanks in advance
You're creating your RKObjectManager instance but you don't provide it with a reference to your managedObjectStore, this is most likely the cause of the issue.

Mutating method sent to immutable object error

Im receiving the next error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '* -[NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
.h file
#property(nonatomic, retain) NSMutableArray *arrayOfBenchmarks;
.m file
- (void)viewDidLoad
{
[super viewDidLoad];
arrayOfBenchmarks = [[NSMutableArray alloc]init];
arrayOfBenchmarks = [self.currentDrill valueForKey:#"benchmarks"];
for (int i=0; i<[arrayOfBenchmarks count]; i++) {
UIButton *benchmarkButton = [UIButton buttonWithType:UIButtonTypeCustom];
benchmarkButton.tag = i;
benchmarkButton.frame = CGRectMake(40,20+(i*55) , 240, 50);
[benchmarkButton setBackgroundImage:[UIImage imageNamed:#"red_color.png"] forState:UIControlStateNormal];
benchmarkButton.titleLabel.textColor = [UIColor blackColor];
benchmarkButton.titleLabel.textAlignment = NSTextAlignmentCenter;
benchmarkButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
NSString *tempString = [[[arrayOfBenchmarks objectAtIndex:i] valueForKey:#"benchmarkTitle"] stringByAppendingString:#"\n"];
[benchmarkButton setTitle:[tempString stringByAppendingString:#"00:00:00"] forState:UIControlStateNormal];
[benchmarkButton addTarget:self action:#selector(onTapBenchmarkButton:)
forControlEvents:UIControlEventTouchUpInside];
// benchmarkButton.enabled = false;
self.btn_scrollView.contentSize = CGSizeMake(0, 50+[arrayOfBenchmarks count]*50);
[arrayOfButtons addObject:benchmarkButton];
[self.btn_scrollView addSubview:benchmarkButton];
dynamicBtnCounter++;
}
}
- (void)onTapBenchmarkButton:(id)sender{
int index = [sender tag];
NSLog(#"index %i", index);
NSString *tempString = [[[arrayOfBenchmarks objectAtIndex:index] valueForKey:#"benchmarkTitle"] stringByAppendingString:#"\n"];
[sender setTitle:[tempString stringByAppendingString:[timerLabel text]] forState:UIControlStateNormal];
[sender setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"green_color.png"]]];
// [sender setBackgroundImage:[UIImage imageNamed:#"green_color.png"]];
NSMutableDictionary *benchmark = (NSMutableDictionary *)[arrayOfBenchmarks objectAtIndex:index];
[benchmark setValue:[timerLabel text] forKey:#"benchmarkPerformedTimer"]; //giving exception at this line
[sender setEnabled:NO];
}
Here is my Benchmark class
#interface Benchmark : NSObject
#property (nonatomic, retain) NSString *bid;
#property (nonatomic, retain) NSString *benchmarkTitle;
#property (nonatomic, retain) NSString *benchmarkDescription;
#property (nonatomic, retain) NSString *benchmarkPerformedTimer;
-(id)initWithCoder: (NSCoder *)coder;
-(void)encodeWithCoder:(NSCoder *)encoder;
#end
I have done it by adding mutable copy:
NSMutableDictionary *benchmark = (NSMutableDictionary *)[[arrayOfBenchmarks objectAtIndex:index] mutableCopy];
[benchmark setValue:[timerLabel text] forKey:#"benchmarkPerformedTimer"];

Core Data - One to Many relationship with object(one) and UIImages(many), storing and fetching

I aim to build a app with the object of:
- Request(contains an unique id, customer name, phone, email, a brief summary of request info, a list of images(store in NSMutable Array)
My Core data contains:
Request
Image
For my request object, I have:
#import <Foundation/Foundation.h>
#interface BAPRequest : NSObject
#property (nonatomic, retain) NSString *requestID;
#property (nonatomic, retain) NSString *name;
#property (nonatomic, retain) NSString *email;
#property (nonatomic, retain) NSString *phone;
#property (nonatomic, retain) NSString *detail;
#property (nonatomic, retain) NSMutableArray *images;
#property (nonatomic, retain) NSDate *requestDate;
#property (nonatomic) BOOL isSent;
- (void)fetchImages;
#end
And the .m File:
#import "BAPAppDelegate.h"
#import "BAPRequest.h"
#implementation BAPRequest
#synthesize name, email, phone, detail;
#synthesize images;
#synthesize requestDate;
#synthesize isSent;
#synthesize requestID;
- (id)init{
self = [super init];
if(self != nil){
self.isSent = false;
self.requestID = [[NSProcessInfo processInfo] globallyUniqueString];
self.images = [[NSMutableArray alloc] init];
}
return self;
}
- (void)fetchImages{
//get delegation
BAPAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
//init request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//load the entity description
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Image"
inManagedObjectContext:context];
//set the request query
[fetchRequest setEntity:entityDescription];
//set predicate to request to ask select specific entity with the matching line num
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(requestId == %#)", self.requestID];
[fetchRequest setPredicate:pred];
//exec the command to find the object(table) from core database
NSArray * imageList = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *imageObject in imageList){
[self.images addObject: [UIImage imageWithData:[imageObject valueForKey:#"content"]]];
}
}
#end
To fetch all the requests, I also do:
- (void)removeRequest:(BAPRequest*)request{
//get delegation
BAPAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
//init request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//load the entity description
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Request"
inManagedObjectContext:context];
//set the request query
[fetchRequest setEntity:entityDescription];
//set predicate to request to ask select specific entity with the matching line num
NSLog(#"request id is %#", request.requestID);
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(requestId LIKE %#)", request.requestID];
[fetchRequest setPredicate:pred];
//exec the command to find the object(table) from core database
NSArray *objects = [context executeFetchRequest:fetchRequest error:&error];
//if this object doesn't exist in the database, it must be something wrong
if (objects == nil) {
NSLog(#"There was an error !");
NSLog(#"Error Info: %#", error);
}
//if object exist in database, take the first search object, and deletes it
if ([objects count] > 0){
NSManagedObject *theRequest = [objects objectAtIndex:0];
[context deleteObject:theRequest];
}
[context save:&error];
/*
//delete existing images relates to this request first
entityDescription = [NSEntityDescription entityForName:#"Image"
inManagedObjectContext:context];
pred = [NSPredicate predicateWithFormat:#"(self.request == %#)", request];
[fetchRequest setPredicate:pred];
NSArray * imageList = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *removeImageObject in imageList){
[context deleteObject:removeImageObject];
}
*/
}
#pragma mark - Convert Core Data Object to Request Object
#pragma mark - Core Data Methods
- (NSMutableArray *)getRequests{
//get app delegate
BAPAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//get object context that's created for us
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//define the entities we want load to description
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Request"
inManagedObjectContext:context];
//init request and set search query to the request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entityDescription];
NSError *error;
//get objects(table) though request
NSArray *objects = [context executeFetchRequest:fetchRequest error:&error];
if (objects == nil){
NSLog(#"There was an error !");
//error handling there
NSLog(#"Error Info: %#", error);
}
NSMutableArray *requests = [[NSMutableArray alloc] init];
for (NSManagedObject *requestObj in objects){
BAPRequest *request = [[BAPRequest alloc] init];
request.requestID = [requestObj valueForKey:#"requestId"];
request.name = [requestObj valueForKey:#"name"];
request.email = [requestObj valueForKey:#"email"];
request.phone = [requestObj valueForKey:#"phone"];
request.detail = [requestObj valueForKey:#"detail"];
request.requestDate = [requestObj valueForKey:#"requestDate"];
request.isSent = [[requestObj valueForKey:#"isSent"] boolValue];
[request fetchImages];
[requests addObject: requestObj];
}
return requests; //return the requests
}
- (void)saveRequest:(BAPRequest *)request{
request.requestDate = [NSDate date];
//get delegation
BAPAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
BAPRequest *theRequest = [NSEntityDescription insertNewObjectForEntityForName:#"Request"
inManagedObjectContext:context];
//set the request obejct basics
[theRequest setValue:request.requestID forKey:#"requestId"];
[theRequest setValue:request.name forKey:#"name"];
[theRequest setValue:request.email forKey:#"email"];
[theRequest setValue:request.phone forKey:#"phone"];
[theRequest setValue:request.detail forKey:#"detail"];
[theRequest setValue:request.requestDate forKey:#"requestDate"];
[theRequest setValue:[NSNumber numberWithBool:request.isSent ] forKey:#"isSent"];
//also save its requests
for (UIImage *img in request.images) {
//init image object
UIImage *newImage=[NSEntityDescription insertNewObjectForEntityForName:#"Image" inManagedObjectContext:context];
[newImage setValue:request.requestID forKey:#"requestId"];
[newImage setValue:UIImagePNGRepresentation(img) forKey:#"content"];
}
[context save:&error]; //save the object
}
#end
My Issue is:
I guess it just doesn't fetch the images at all. Even they fetched the images in the getRequests method, when I try to pass the request to somewhere else, it still get lots issues:
boolean not loading properly
images are nil(even it was loaded when fetch)
and the reason is(I can be wrong) that when I store these request objects(BAPRequest*) into a NSArray and pass it to a table view, when I load them from array (e.g [myArray objectAtIndex:0]), they are still NSManagedObject. I tried to give a class name in the core data entity option to make the Request(Core Data) Object Class of BAPRequest, but it keeps saying I have to subclass NSManagedObject, where subclassing NSManagedObject is not possible:
I can't do:
BAPRequest: NSManagedObject
XCode doesn't likes it.
Look at mogenerator. Here's a tutorial on how to use it: http://raptureinvenice.com/getting-started-with-mogenerator/ . It will save you a lot of trouble.

Resources