Mutating method sent to immutable object error - nsmutablearray

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"];

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.

CoreData: error: Failed to call designated initializer on NSManagedObject class while using NSCoding

I keep getting this error when run my app: "CoreData: error: Failed to call designated initializer on NSManagedObject class "Ambulance"". I've seen this problem on stack overflow already but im unsure of how to implement a solution in my case. Any ideas?
Ambulance.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface Ambulance : NSManagedObject
#property (nonatomic, retain) NSString * ambulanceID;
#property (nonatomic, retain) NSNumber * distance;
#property (nonatomic, retain) NSNumber * etaDistance;
#property (nonatomic, retain) NSString * emsID;
#property (nonatomic, retain) NSString * lat;
#property (nonatomic, retain) NSString * lng;
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSNumber * occupancy;
#property (nonatomic, retain) NSString * type;
#property (nonatomic, retain) NSString * websocketServer;
#property (nonatomic, retain) NSNumber * seconds;
#property (nonatomic, retain) id eta;
+(Ambulance *)nearestAmbulanceByType:(NSString *)type;
- (id)initWithCoder:(NSCoder *)decoder;
- (void)encodeWithCoder:(NSCoder *)encoder;
#end
Ambulance.m
#import "Ambulance.h"
#implementation Ambulance
#synthesize ambulanceID;
#synthesize distance;
#synthesize etaDistance;
#synthesize emsID;
#synthesize lat;
#synthesize lng;
#synthesize name;
#synthesize occupancy;
#synthesize type;
#synthesize websocketServer;
#synthesize seconds;
#synthesize eta;
+(Ambulance *)nearestAmbulanceByType:(NSString *)type {
NSArray *sortedArray = [Ambulance findByAttribute:#"type" withValue:type andOrderBy:#"distance" ascending:YES];
return [sortedArray first];
}
- (void)encodeWithCoder:(NSCoder *)encoder {
//Encode properties, other class variables, etc
[encoder encodeObject:self.ambulanceID forKey:#"ambulanceID"];
[encoder encodeObject:self.distance forKey:#"distance"];
[encoder encodeObject:self.etaDistance forKey:#"etaDistance"];
[encoder encodeObject:self.emsID forKey:#"emsID"];
[encoder encodeObject:self.lat forKey:#"lat"];
[encoder encodeObject:self.lng forKey:#"lng"];
[encoder encodeObject:self.name forKey:#"name"];
[encoder encodeObject:self.occupancy forKey:#"occupancy"];
[encoder encodeObject:self.type forKey:#"type"];
[encoder encodeObject:self.websocketServer:#"websocketServer"];
[encoder encodeObject:self.seconds forKey:#"seconds"];
[encoder encodeObject:self.eta forKey:#"eta"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
//decode properties, other class vars
self.ambulanceID = [decoder decodeObjectForKey:#"ambulanceID"];
self.distance = [decoder decodeObjectForKey:#"distance"];
self.etaDistance = [decoder decodeObjectForKey:#"etaDistance"];
self.emsID = [decoder decodeObjectForKey:#"emsID"];
self.lat = [decoder decodeObjectForKey:#"lat"];
self.lng = [decoder decodeObjectForKey:#"lng"];
self.name = [decoder decodeObjectForKey:#"name"];
self.occupancy = [decoder decodeObjectForKey:#"occupancy"];
self.type = [decoder decodeObjectForKey:#"type"];
self.websocketServer = [decoder decodeObjectForKey:#"websocketServer"];
self.seconds = [decoder decodeObjectForKey:#"seconds"];
self.eta = [decoder decodeObjectForKey:#"eta"];
}
return self;
}
You should use any other initializer than initWithEntity:insertIntoManagedObjectContext: for your NSManagedObject subclass.
From the docs:
Important: This method is the designated initializer for
NSManagedObject. You must not initialize a managed object simply by
sending it init.
Are you sure you have to use NSCoding with your subclass? It would probably be sufficient to store the objectID since your object exists in a NSManagedObjectContext and probably gets persisted anyways.
If you really rely on NSCoding you have to determine and feed the proper NSManagedObjectContext to initWithEntity:insertIntoManagedObjectContext: in initWithCoder:.
Not sure what this has to do with RestKit and why you think you need to support coding.
Assuming you are using RestKit though, you should be able to change to:
- (id)initWithCoder:(NSCoder *)decoder {
NSManagedObjectContext *moc = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Ambulance" inManagedObjectContext:moc];
if((self = [super initWithEntity:entity insertIntoManagedObjectContext:moc])) {
...
If you aren't using RestKit then you'll need a different way to get the MOC.

Restkit 0.20 pre4 core data issue

{"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.

Resources