I have to main issues that I believe are related as they both occur on the same line of code.
Data Model
NB: I have simplified the code and model as best I can.
I have 3 entities in my Core data model.
Merchant (can have many Branches, can have many Sectors)
Sector (can have many Merchants)
Branch (can have one Merchant)
Data is downloaded (in JSON) to the app. Each Merchant is iterated over sectors are extracted, if the sector exists it is fetched and added to a NSMutableArray.
...
//Iterating through Merchants
...
for(NSDictionary *sector in sectors) {
NSLog(#"\tfetch sectors ID %#", [sector objectForKey:#"sector_id"]);
NSPredicate *sectorPredicate = [NSPredicate predicateWithFormat:#"%K == %d", #"sectorID", [[sector objectForKey:#"sector_id"] integerValue]];
[sectorRequest setPredicate:sectorPredicate];
NSArray *existingSector = [self.managedObjectContext executeFetchRequest:sectorRequest error:&error];
if(!error && [existingSector count] == 1) {
NSLog(#"\tfound sector");
[merchantSectors addObject:[existingSector objectAtIndex:0]];
}
else {
NSLog(#"\tcreate a new sector");
//Create a new sector
Sector *newSector = [[Sector alloc] initWithEntity:sectorEntity insertIntoManagedObjectContext:self.managedObjectContext];
newSector.sectorID = [NSNumber numberWithInteger:[[sector objectForKey:#"sector_id"] integerValue]];
newSector.name = [sector objectForKey:#"name"];
[merchantSectors addObject:newSector];
[newSector release]; newSector = nil;
}
}
[sectorRequest release]; sectorRequest = nil;
NSLog(#"\tadd sectors to merchant");
[currentMerchant addSector:merchantSectors]; //<---- crash and hang
The App will either hang at:
[currentMerchant addSector:merchantSectors];
or sometimes throw an exception:
*** Terminating app due to uncaught exception \
'NSInternalInconsistencyException', reason: \
'-[__NSCFSet addObject:]: mutating method sent to immutable object'
The Branch parsing code is almost identical but never has these issues or the app will hang or crash before it becomes an issue (??).
If the App is deleted and reinstalled the code will work fine, is it possible that existing identical relationships are causing this problem?
Edit: The parsing of the JSON is called using an NSInvocationOperation, so when it hangs the interface stays responsive. The crash version kills the app.
Edit 2: Merchant.h and Merchant.m
Merchant.h
#import <CoreData/CoreData.h>
#class Branch;
#class Sector;
#interface Merchant : NSManagedObject
{
}
#property (nonatomic, retain) NSString * street;
#property (nonatomic, retain) NSString * locality;
#property (nonatomic, retain) NSString * city;
#property (nonatomic, retain) NSNumber * merchantID;
#property (nonatomic, retain) NSString * postcode;
#property (nonatomic, retain) NSString * property;
#property (nonatomic, retain) NSString * organisation;
#property (nonatomic, retain) NSDate * expires;
#property (nonatomic, retain) NSSet * Branch;
#property (nonatomic, retain) NSSet* Sector;
#end
#interface Merchant (CoreDataGeneratedAccessors)
- (void)addBranchObject:(Branch *)value;
- (void)removeBranchObject:(Branch *)value;
- (void)addBranch:(NSSet *)value;
- (void)removeBranch:(NSSet *)value;
- (void)addSectorObject:(Sector *)value;
- (void)removeSectorObject:(Sector *)value;
- (void)addSector:(NSSet *)value;
- (void)removeSector:(NSSet *)value;
#end
Merchant.m
#import "Merchant.h"
#import "Branch.h"
#implementation Merchant
#dynamic street;
#dynamic locality;
#dynamic city;
#dynamic merchantID;
#dynamic postcode;
#dynamic property;
#dynamic organisation;
#dynamic expires;
#dynamic Branch;
#dynamic Sector;
#end
Try to add Sectors to Merchant one by one using CoreData add<Key>Object: and remove<Key>Object: auto-generated methods (as described in Custom To-Many Relationship Accessor Methods)
for(NSDictionary *sector in sectors) {
NSPredicate *sectorPredicate = [NSPredicate predicateWithFormat:#"%K == %d", #"sectorID", [[sector objectForKey:#"sector_id"] integerValue]];
[sectorRequest setPredicate:sectorPredicate];
NSArray *existingSector = [self.managedObjectContext executeFetchRequest:sectorRequest error:&error];
if(!error && [existingSector count] == 1)
{
[currentMerchant addSectorObject:[existingSector lastObject]];
}
else
{
Sector *newSector = [[Sector alloc] initWithEntity:sectorEntity insertIntoManagedObjectContext:self.managedObjectContext];
newSector.sectorID = [NSNumber numberWithInteger:[[sector objectForKey:#"sector_id"] integerValue]];
newSector.name = [sector objectForKey:#"name"];
[currentMerchant addSectorObject:newSector];
[newSector release];
}
}
Or you can retrieve mutable proxy object contains currentMerchants's sectors via mutableSetValueForKey: and add sectors to it:
NSMutableSet *merchantSectors = [currentMerchant mutableSetValueForKey:#"sector"];
for(NSDictionary *sector in sectors) {
NSPredicate *sectorPredicate = [NSPredicate predicateWithFormat:#"%K == %d", #"sectorID", [[sector objectForKey:#"sector_id"] integerValue]];
[sectorRequest setPredicate:sectorPredicate];
NSArray *existingSector = [self.managedObjectContext executeFetchRequest:sectorRequest error:&error];
if(!error && [existingSector count] == 1)
{
[merchantSectors addObject:[existingSector lastObject]];
}
else
{
Sector *newSector = [[Sector alloc] initWithEntity:sectorEntity insertIntoManagedObjectContext:self.managedObjectContext];
newSector.sectorID = [NSNumber numberWithInteger:[[sector objectForKey:#"sector_id"] integerValue]];
newSector.name = [sector objectForKey:#"name"];
[merchantSectors addObject:newSector];
[newSector release];
}
}
Anyway, for convenience it's better to use lowercase sectors name for Mecrhant entity for to-many relationship with Sector entity: lowercase not to be ambiguous with Sector class name, and with s at and to be sure, that getter methods for this property return multiple objects.
Related
I'm quite new to Objective-C. I've been trying to fetch from my core data entity. The following code fetches the right row because it only returns 1 result.
but when I try to NSlog() it to see its values what I get is:
iGym[3922:c07] (
"<User: 0x8397690> (entity: User; id: 0x8341580 <x-coredata://114815EF-85F4-411F-925B-8479E1A94770/User/p19> ; data: <fault>)"
)
I am used to PHP that I just do a var_dump() and i get all the information in the array... specially when I am expecting 16 results as this entity has 16 fields.
Could anyone tell me how could I inspect that array?
and also, most important, how do I ultimately do this: fetch the Gender field of the matched email field and assign it to a NSString variable.
The query i want to do in sql is SELECT Gender FROM myTable WHERE email = "something#something.com;
-(NSInteger*)selectedGenderMethod
{
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"User" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
request.predicate = [NSPredicate predicateWithFormat:#"email = %#",_currentUser];
NSError *error = nil;
NSArray *matches = [[context executeFetchRequest:request error:&error] mutableCopy];
NSString * someVar= [matches[0] objectForKey:#"email"];
NSLog(#"%#",someVar);
//More to come once this is sorted
return 0;
}
This fetching code is happening in my genderPickerViewController : UIViewController
NSLog(#"%#", matches[0]);
returns
<User: 0x83a6b00> (entity: User; id: 0x83995f0 <x-coredata://114815EF-85F4-411F-925B-8479E1A94770/User/p19> ; data: <fault>)
This is my User.h:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface User : NSManagedObject
#property (nonatomic, retain) NSDate * dob;
#property (nonatomic, retain) NSString * email;
#property (nonatomic, retain) NSNumber * firstTime;
#property (nonatomic, retain) NSString * gender;
#property (nonatomic, retain) NSString * height;
#property (nonatomic, retain) NSNumber * idFB;
#property (nonatomic, retain) NSNumber * idUserExternal;
#property (nonatomic, retain) NSNumber * idUserInternal;
#property (nonatomic, retain) NSNumber * isPT;
#property (nonatomic, retain) NSString * language;
#property (nonatomic, retain) NSString * metricSystem;
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSString * nickname;
#property (nonatomic, retain) NSString * password;
#property (nonatomic, retain) NSString * surname;
#property (nonatomic, retain) NSString * weight;
#end
User.m:
#implementation User
#dynamic dob;
#dynamic email;
#dynamic firstTime;
#dynamic gender;
#dynamic height;
#dynamic idFB;
#dynamic idUserExternal;
#dynamic idUserInternal;
#dynamic isPT;
#dynamic language;
#dynamic metricSystem;
#dynamic name;
#dynamic nickname;
#dynamic password;
#dynamic surname;
#dynamic weight;
#end
Is the user object a NSDictionary or an NSArray by chance? If that is the case you are simply logging out the object, you will need to specify a specific entity in the object to output.
For example if it's a NSDictionary
NSString *name = [matches[0] objectForKey:#"name"];
NSLog("Name %#", name);
You could also try
NSString *email = (User *)matches[0].email;
NSLog("Email %#", email);
What you are doing is right, you usually get the full objects and not only one attribute, Core Data is an object storage.
So you only need [((User *)matches[0]) gender] to get the gender of the returned user.
If you want to get some extra information from objects you must implement:
- (NSString *)description
It is used for converting to string and logging.
You can use the following code,
[NSPredicate predicateWithFormat:#"email CONTAINS[c] %#", _currentUser];
OR
[NSPredicate predicateWithFormat:#"email CONTAINS[cd] %#", _currentUser];
then you can print the fetched results as type po OBJECT_NAME.PROPERTY in debug area
I want to serialize array to JSON.
Here is my JSON -
{
"User":{"Id":"1222","Email":"asdad#adasd.com"},
"Person":{"Name":"John","Surname":"Smith"}
}
values 1222, asdad#adasd.com, John, Smith are examples. this values will be define in controller.
I don't know how to handle serialize this arrays inside JSON.
I need to send objects - user and person to the server with different values, depending on the user. This is my model. Both are arrays.
Here is my code
Header
#import <Foundation/Foundation.h>
#import "BaseRequest.h"
#interface SaveUserProfileRequest : BaseRequest {
NSMutableArray *_user;
NSMutableArray *_person;
NSMutableArray *_address;
NSString *_userId;
NSString *_userEmail;
NSString *_userName;
NSString *_userSurname;
}
- (id)initWithUser:(NSMutableArray*)user andPerson:(NSMutableArray*)person andAddress:(NSMutableArray*)address andUserId:(NSString*)userId andUserEmail:(NSString*)userEmail andUserName:(NSString*)userName andUserSurname:(NSString*)userSurname;
#property (nonatomic, strong) NSMutableArray* user;
#property (nonatomic, strong) NSMutableArray* person;
#property (nonatomic, strong) NSMutableArray* address;
#property (nonatomic, strong) NSString* userId;
#property (nonatomic, strong) NSString* userEmail;
#property (nonatomic, strong) NSString* userName;
#property (nonatomic, strong) NSString* userSurname;
#end
Implementation
#import "SaveUserProfileRequest.h"
#import "SaveUserProfileResponse.h"
#import "OrderedDictionary.h"
#import "BaseData.h"
#implementation SaveUserProfileRequest
#synthesize user=_user, person=_person, address=_address, userId=_userId, userEmail=_userEmail, userName=_userName, userSurname=_userSurname;
- (id)initWithUser:(NSMutableArray*)user andPerson:(NSMutableArray*)person andAddress:(NSMutableArray*)address andUserId:(NSString*)userId andUserEmail:(NSString*)userEmail andUserName:(NSString*)userName andUserSurname:(NSString*)userSurname; {
self = [super init];
if(self){
self.user = user;
self.person = person;
self.address = address;
self.userId = userId;
self.userEmail = userEmail;
self.userName = userName;
self.userSurname = userSurname;
}
return self;
}
- (NSDictionary*) serialize{
OrderedDictionary *sup = [OrderedDictionary dictionaryWithCapacity:3];
[sup setValue:self.user forKey:#"User"];
[sup setValue:self.person forKey:#"Person"];
NSArray *users = [OrderedDictionary valueForKey:#"User"];
_user = [NSMutableArray arrayWithCapacity:[users count]];
for(NSDictionary *user in users){
OrderedDictionary *userDict = [OrderedDictionary dictionaryWithCapacity:2];
[userDict setValue:self.userId forKey:#"Id"];
[userDict setValue:self.userEmail forKey:#"Mail"];
return userDict;
}
NSArray *persons = [OrderedDictionary valueForKey:#"Person"];
_person = [NSMutableArray arrayWithCapacity:[persons count]];
for(NSDictionary *person in persons){
OrderedDictionary *personsDict = [OrderedDictionary dictionaryWithCapacity:2];
[personsDict setValue:self.userName forKey:#"Name"];
[personsDict setValue:self.userSurname forKey:#"Surname"];
return personsDict;
}
return sup;
}
Please, help me a little
Every little hint will be really appreciate.
Thanks !
For handeling JSON in Objective-C, I always use JSONKit. You can fork it here: https://github.com/johnezang/JSONKit
Some examples on how it can be used:
NSArray *array = #[..];
NSString *arrayAsJsonString = [array JSONString];
NSString *string = #"..";
id objectFromJsonString = [string objectFromJSONString]; // i.e an NSArray or NSDictionary
If your app is for iOS 5 or greater, you can use NSJSONSerialization:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
Otherwise I recommend SBJson.
Help!!!I have a one-to-many relationship.
Why does [self.menu addSubMenuObject:newSubMenu] not work?
ManagerCoreData * managerCoreData = (ManagerCoreData *)[ManagerCoreData sharedInstance];
NSManagedObjectContext * managedObjectContex = managerCoreData.managedObjectContext;
SubMenu * newSubMenu =(SubMenu*) [NSEntityDescription insertNewObjectForEntityForName:#"SubMenu" inManagedObjectContext:managedObjectContex];
[self.menu addSubMenuObject:newSubMenu];
if (newSubMenu != nil){
newSubMenu.name = self.textFieldName.text;
newSubMenu.cost = [NSNumber numberWithInteger:[self.textFieldCost.text integerValue]];
newSubMenu.about = self.textFieldAbout.text;
newSubMenu.imageOriginal = self.imageView.image;
NSError * savingError = nil;
if ([managedObjectContex save:&savingError]){
[self.navigationController popViewControllerAnimated:YES];
}else {
NSLog(#"Failed to save manager object contex!!!Error %#",savingError);
}
}else {
NSLog(#"Failed to create new object!!!");
}
#class SubMenu;
#interface Menu : NSManagedObject
#property (nonatomic, retain) NSData * imageMiddle;
#property (nonatomic, retain) id imageOriginal;
#property (nonatomic, retain) NSData * imageSmall;
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSSet *subMenu;
#end
#interface Menu (CoreDataGeneratedAccessors)
- (void)addSubMenuObject:(SubMenu *)value;
- (void)removeSubMenuObject:(SubMenu *)value;
- (void)addSubMenu:(NSSet *)values;
- (void)removeSubMenu:(NSSet *)values;
#end
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SubMenu menu]: unrecognized selector sent to instance 0x74caf90'
I have a fairly simple iPhone app which utilizes CoreData for object persistence.
The object has, amongst other attributes, an NSNumber attribute, defined in the datamodel along with all the other attributes. I set this during the application run cycle to 1 if the user clicks on a particular button. I then call the store function which definitely does get called, and is the same function as persisted everything else, and this seems to work temporarily, in that if I check the value of the attribute on my NSManagedObject it has the correct value, if I retrieve the object from the data store and check it it still has the right value. However if I restart the app, it has not persisted, and so it reverts to the default. I'm getting quite frustrated and have tried various methods of forcing the ManagedObjectContext to persist.
Relevant code:
Persistence code...
- (Area*) storeAreaFavourite:(Area*)a
{
a = [self storeArea:a];
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
//[context refreshObject:a mergeChanges:YES];
[context processPendingChanges];
NSLog(#"Stored area with favourite: %#",([a favourite] != nil ? [a favourite] : [NSNumber numberWithInt: 0]));
return a;
}
- (Area*) storeArea:(Area*)a
{
NSError *error = nil;
// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSFetchRequest* request = [[NSFetchRequest alloc] init];
NSEntityDescription* entity = [NSEntityDescription entityForName:#"Area" inManagedObjectContext:context];
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"areaId=%#", [a areaId]];
[request setEntity:entity];
[request setPredicate:predicate];
NSArray* matchedAreas = [context executeFetchRequest:request error:&error];
if (error != nil)
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
//NSLog(#"Matched %d Areas", [matchedAreas count]);
Area* newArea = [matchedAreas count] > 0 ? [matchedAreas objectAtIndex:0] : nil;
if (newArea == nil)
{
newArea = [NSEntityDescription insertNewObjectForEntityForName:#"Area" inManagedObjectContext:context];
}
else {
//NSLog(#"Area: %# -> %# ParentArea: %# -> %#", [newArea valueForKey:#"areaId"], [a areaId], [(Area*)[newArea valueForKey:#"parentArea"] areaId], [(Area*)[a parentArea] areaId]);
}
// If appropriate, configure the new managed object.
[newArea setValue:[a areaId] forKey:#"areaId"];
[newArea setValue:[a areaName] forKey:#"areaName"];
[newArea setValue:[a parentArea] forKey:#"parentArea"];
[newArea setValue:[a height] forKey:#"height"];
[newArea setValue:[a width] forKey:#"width"];
[newArea setValue:[a xPos] forKey:#"xPos"];
[newArea setValue:[a yPos] forKey:#"yPos"];
[newArea setValue:[a childAreas] forKey:#"childAreas"];
[newArea setValue:[a imageName] forKey:#"imageName"];
[newArea setValue:[a areaText] forKey:#"areaText"];
[newArea setValue:([a favourite] != nil ? [a favourite] : [NSNumber numberWithInt: 0]) forKey:#"favourite"];
if ([a favourite] != nil && [[NSNumber numberWithInt:1] isEqualToNumber:[a favourite]])
{
NSLog(#"Storing area with areaId: %#",[a areaId]);
NSLog(#"Storing area with areaName: %#",[a areaName]);
NSLog(#"Storing area with parentArea: %#",[a parentArea]);
NSLog(#"Storing area with height: %#",[a height]);
NSLog(#"Storing area with width: %#",[a width]);
NSLog(#"Storing area with xPos: %#",[a xPos]);
NSLog(#"Storing area with yPos: %#",[a yPos]);
NSLog(#"Storing area with childAreas: %#",[a childAreas]);
NSLog(#"Storing area with imageName: %#",[a imageName]);
NSLog(#"Storing area with areaText: %#",[a areaText]);
NSLog(#"Storing area with favourite: %#",([a favourite] != nil ? [a favourite] : [NSNumber numberWithInt: 0]));
}
// Save the context.
if (![context save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
//abort();
}
matchedAreas = [context executeFetchRequest:request error:&error];
if (error != nil)
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
//NSLog(#"Matched %d Areas", [matchedAreas count]);
newArea = [matchedAreas count] > 0 ? [matchedAreas objectAtIndex:0] : nil;
if (newArea != nil)
{
NSLog(#"StoredFav:%#:%#",[newArea areaId],[newArea favourite]);
}
return newArea;
}
Area.m
//
// Area.m
// MappApp
//
// Created by Matthew Fellows on 27/07/2011.
//
#import "Area.h"
#implementation Area
#synthesize height;
#synthesize areaId;
#synthesize xPos;
#synthesize areaName;
#synthesize width;
#synthesize areaText;
#synthesize imageName;
#synthesize yPos;
#synthesize childAreas;
#synthesize parentArea;
#synthesize areaImages;
#synthesize favourite;
- (void)addChildAreasObject:(NSManagedObject *)value{
if (childAreas == nil)
{
childAreas = [[NSMutableSet alloc] init];
}
[childAreas addObject:value];
}
- (void)addAreaImagesObject:(NSManagedObject *)value{
if (areaImages == nil)
{
areaImages = [[NSMutableSet alloc] init];
}
[areaImages addObject:value];
}
#end
Area.h
//
// Area.h
// MappApp
//
// Created by Matthew Fellows on 27/07/2011.
//
#import <CoreData/CoreData.h>
#interface Area : NSManagedObject
{
NSMutableSet* areaImages;
NSMutableSet* childAreas;
}
#property (nonatomic, retain) NSNumber * height;
#property (nonatomic, retain) NSNumber * areaId;
#property (nonatomic, retain) NSNumber * xPos;
#property (nonatomic, retain) NSString * areaName;
#property (nonatomic, retain) NSNumber * width;
#property (nonatomic, retain) NSString * areaText;
#property (nonatomic, retain) NSString * imageName;
#property (nonatomic, retain) NSNumber * yPos;
#property (nonatomic, retain) NSMutableSet* childAreas;
#property (nonatomic, retain) NSManagedObject * parentArea;
#property (nonatomic, retain) NSMutableSet* areaImages;
#property (nonatomic, retain) NSNumber* favourite;
#end
#interface Area (CoreDataGeneratedAccessors)
- (void)addChildAreasObject:(NSManagedObject *)value;
- (void)removeChildAreasObject:(NSManagedObject *)value;
- (void)addChildAreas:(NSSet *)value;
- (void)removeChildAreas:(NSSet *)value;
- (void)addAreaImagesObject:(NSManagedObject *)value;
- (void)removeAreaImagesObject:(NSManagedObject *)value;
- (void)addAreaImages:(NSSet *)value;
- (void)removeAreaImages:(NSSet *)value;
#end
You have #synthesized your accessors for what are presumably managed object properties. This means they won't be passing through the correct core data accessors and will not be updating your model properly. #dynamic should be used to tell the compiler that the proper accessors will be available at run time (the core data framework will be providing them).
I think with what you have now you have basically made all of your attributes transient.
You should make all your properties #dynamic.
The #synthesize will create a getter and setter for each property, but will do nothing for the CoreData storage system.
That is, changing the values will not cause CoreData to know they have changed, and thus to store them.
I've this simple Core Data Model:
Question, Answer
Every every question has 4 answers.
The code is the following:
Question.m
#interface Question : NSManagedObject
{
}
#property (nonatomic, retain) NSString * questionText;
#property (nonatomic, retain) NSSet* answers;
#property (nonatomic, retain) Package * package;
#end
#interface Question (CoreDataGeneratedAccessors)
- (void)addAnswersObject:(NSManagedObject *)value;
- (void)removeAnswersObject:(NSManagedObject *)value;
- (void)addAnswers:(NSSet *)value;
- (void)removeAnswers:(NSSet *)value;
#end
Answer.m
#class Question;
#interface Answer : NSManagedObject
{
}
#property (nonatomic, retain) NSString * answerText;
#property (nonatomic, retain) NSNumber * correct;
#property (nonatomic, retain) Question * question;
#end
The problem is when i try to add an answer to a question with addAnswersObject.
This is the part of the code that crash the app:
for (CXMLElement *theElement in theNodes)
{
Question *qst = [NSEntityDescription insertNewObjectForEntityForName:#"Question" inManagedObjectContext:moc];
// Create a counter variable as type "int"
int counter;
// Loop through the children of the current node
for(counter = 0; counter < [theElement childCount]; counter++) {
if([[[theElement childAtIndex:counter] name] isEqualToString: #"question"])
[qst setQuestionText:[[theElement childAtIndex:counter] stringValue]];
if([[[theElement childAtIndex:counter] name] isEqualToString: #"answer"]) {
Answer *answer = [NSEntityDescription insertNewObjectForEntityForName:#"Answer" inManagedObjectContext:moc];
[answer setAnswerText:[[theElement childAtIndex:counter] stringValue]];
CXMLElement *answerElement = (CXMLElement *)[theElement childAtIndex:counter];
if([[[answerElement attributeForName:#"correct"] stringValue] isEqualToString:#"YES"]) {
[answer setCorrect:[NSNumber numberWithBool:YES]];
} else {
[answer setCorrect:[NSNumber numberWithBool:NO]];
}
[qst addAnswersObject:answer]; //The app crash here
}
}
This is the log from console:
2010-05-24 20:02:38.475 Fgq[5670:40b]
*** -[NSUserDefaults objectForKey:]: message sent to deallocated instance
0x3c179a0 Program received signal:
“EXC_BAD_ACCESS”.
I re-exported many times all objects from the Object Data Model without success, I've checked all relationships and it seems that everything is ok.
What kind of problem could be?
What does the Console report if you add NSLog(#"qst: %#:, qst); immediately after the qst instance's -insertNewObjectForEntityName:inManagedObjectContext: call?
What does the Console report if you add NSLog(#"answer: %#:, answer); immediately after the answer instance's -insertNewObjectForEntityName:inManagedObjectContext: call?
Here what is reported with NSLog(#"qst: %#", qst);
2010-05-24 23:37:33.948
FGQ[452:207] qst:
(entity:
Question; id: 0x3c19ab0
; data: {
answers = (
);
package = nil;
questionText = nil; })