CoreData errors for simple adding to database - ios

Edit: The error messages that I am trying to figure out are on the right side of the code listed as comments!!!
Xcode keeps trying to suggest alternatives and refusing to let me build. The 3 are listed in comment tags on the right side of the code. What do they mean? I am very new to using core data and really hoping to see what I am doing wrong, just using username as an example (as I know I shouldn't be doing so)!
- (IBAction)saveData:(id)sender {
NSManagedObjectContext *cxt = [self managedObjectContext]; //instance method managedObjectContext not found
NSManagedObject *newContacts = [NSEntityDescription insertNewObjectForEntityForName:#"Contacts" inManagedObjectContext:cxt];
[newContacts setValue:self.username.text forKey:#"username"]; //insert NSManagedObjectModel instead of NSManagedObject...claims that it is undeclared?
username.text = #"";
NSManagedObject *newContacts = [NSEntityDescription insertNewObjectForEntityForName:#"Contacts" inManagedObjectContext:cxt]; //trying to replace NSEntityDescription with KSecAttrDescription...claims that it is undeclared
[newContacts setValue:self.password.text forKey:#"password"];
password.text = #"";
NSError *err;
if (![cxt save:&err]) {
NSLog(#"An error has occured: %#", [err localizedDescription]); //Instance Method -save not found
}
}

CoreData code looks good, but you are using NSManagedObject *newContacts twice, just use another variable name or remove NSManagedObject * for the second object.
Also i would recommend you to make classes for your objects to have a direct access to variables instead of [obj setValue:value forKey:#"key"];
And of course it would be nice to see the error output.

Solved it! However, it was from a previous answer for this question who removed them self, so I'm giving the credit to that unknown person. If anybody has this error in the future, click on you core data.xcdatamoldeld, then click on the Editor section on your menu bar (of your desktop), then click set NSManagedObject Subclass and add them. It should work then.

Related

Core Data Entity Created But Attributes Not Saving

I have a relatively simple entity. When I create it, set its attributes, and save it, it saves successfully. I can later retrieve it and it is not nil and I get a successful save message from MagicalRecord.
When I retrieve it and try to access any attribute though the attribute is nil. The entity itself is fine but the attributes are all nil. I have checked they are all definitely set correctly before I save.
I haven't encountered this problem before. Why could it be occurring?
NB: This doesn't happen every time. Most times I call the method to create and save this entity it can later be retrieved without any issues. The problem is intermittent but possible to replicate on every run.
Code:
Entity1 *entity1 = [Entity1 MR_createEntityInContext:localContext];
[entity1 setUpEntity:myobject];
EntityChild *entityChild=[EntityChild MR_createEntityInContext:localContext];
[entityChild setUpEntityChild:entity.child withContext:localContext];
[entityChild setEntity1:entity1];
[localContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
}];
Update:
If I look in the sqlite database and search for the entity it actually doesn't exist at all. So MagicalRecord tells me it saves, CoreData lets me retrieve a non-nil object (albeit with nil attributes) but no record exists in the database.
I did not understand ur code standards. As I am new to IOS Development. I Used below code for retrieving.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityRef = [NSEntityDescription entityForName:#"Entity1" inManagedObjectContext:appDelegate.managedObjectContext];//localContext
[fetchRequest setEntity:entityRef];
NSError *error=nil;
NSArray *detailsArray = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(#"Unable to execute fetch request.");
NSLog(#"%#, %#", error, error.localizedDescription);
}
Saving the data
NSManagedObjectContext *context = [appDelegate managedObjectContext];//localContext
NSManagedObject *objectRef = [NSEntityDescription
insertNewObjectForEntityForName:#"Entity1" inManagedObjectContext:context];
[objectRef setValue:#"IOS" forKey:#"Name"];
[objectRef setValue:#"positive" forKey:#"Attitude"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
Hope it helps you...!
Ok, I got to the bottom of this. It wasn't a problem with the code when I did the save. It was actually a problem with some code in another class that was retrieving the data from the wrong context. When I changed the context it worked correctly.
I'm still not sure why this only happened occasionally and not every time the code was run but it's working now.
Thanks for your help anyway everyone.

Core Data entity error with xmpp

I am using XMPP Framework's Core Data message storage and I want to add to my app another Core Data Entity, I create .xcdatamodeld and create Entity, I add code to my AppDelegate, but I get error. Can it be because I use XMPP Framework's Core Data message storage and how to fix it?
NSManagedObjectContext *context = [self managedObjectContext_messageList];
NSManagedObject *contexNew = [NSEntityDescription insertNewObjectForEntityForName:#"UserProfileEntity" inManagedObjectContext:context];
[contexNew setValue:#1 forKey:#"id"];
[contexNew setValue:#"name TEST" forKey:#"name"];
[contexNew setValue:#"test YEP" forKey:#"test"];
NSError *error;
if ([context save:&error])
{
NSLog(#"%#", error.description);
}
It crashes on on second line with
'+entityForName: nil is not a legal NSManagedObjectContext parameter
searching for entity name 'UserProfileEntity''
That error means that nil is not a legal thing to pass for the managed object context. So, did you inject the context in the correct manner? I mean that the following line
NSManagedObjectContext *context = [self managedObjectContext_messageList];
should have a counterpart like
yourController.managedObjectContext_messageList = theContextYouWantToInject;
or
[yourController setManagedObjectContext_messageList:theContextYouWantToInject];
If you are using segues here a useful discussion: '+entityForName: nil is not a legal NSManagedObjectContext parameter - Core Data.
In addition, are you sure you are providing a valid store coordinator? For further references take a look to The Core Data Stack.

MagicalRecord does not save data

I am trying my hand at some very basic implementation of MagicalRecord to get the hang of it and run into the following.
When I save an entry and then fetch entries of that type it will come up with the entry I just saved. However, when I save the entry, close the app, start it again, and then fetch, it comes up empty.
Code for saving:
- (void)createTestTask{
NSManagedObjectContext *localContext = [NSManagedObjectContext contextForCurrentThread];
Task *task = [Task createInContext:localContext];
task.tName = #"First Task";
task.tDescription = #"First Task created with MagicalRecord. Huzzah!";
NSError *error;
[localContext save:&error];
if (error != Nil) {
NSLog(#"%#", error.description);
}
}
Code for fetching: (all I want to know here if anything is actually saved)
- (void) fetchTasks{
NSArray *tasks = [Task findAll];
NSLog(#"Found %d tasks", [tasks count]);
}
I am sure I am missing something here, but not anything I can seem to find on stackoverflow or in the Tutorials I looked at.
Any help is welcome.
I have to ask the obvious "Is it plugged in" question: Did you initialize the Core Data Stack with one of the +[MagicalRecord setupCoreDataStack] methods?
Did your stack initialize properly? That is, is your store and model compatible? When they aren't, MagicalRecord (more appropriately, Core Data) will set up the whole stack without the Persistent Store. This is annoying because it looks like everything is fine until it cannot save to the store...because there is no store. MagicalRecord has a +[MagicalRecord currentStack] method that you can use to examine the current state of the stack. Try that in the debugger after you've set up your stack.
Assuming you did that, the other thing to check is the error log. If you use
[localContext MR_saveToPersistentStoreAndWait];
Any errors should be logged to the console. Generally when you don't see data on a subsequent run of your app, it's because data was not saved when you thought you called save. And the save, in turn, does not happen because your data did not validate correctly. A common example is if you have a required property, and it's still nil at the time you call save. "Normal" core data does not log these problems at all, so you might think it worked, when, in fact, the save operation failed. MagicalRecord, on the other hand, will capture all those errors and log them to the console at least telling you what's going on with your data.
When i have started with magical record I was also facing this problem, problem is context which you are using to save data. here is my code which might help you
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
NSArray *userInfoArray = [UserBasicInfo findByAttribute:#"userId" withValue:[NSNumber numberWithInt:loggedInUserId] inContext:localContext];
UserBasicInfo* userInfo;
if ([userInfoArray count]) {
userInfo = [userInfoArray objectAtIndex:0];
} else {
userInfo = [UserBasicInfo createInContext:localContext];
}
userInfo.activeUser = [NSNumber numberWithBool:YES];
userInfo.firstName = self.graphUser[#"first_name"];
userInfo.lastName = self.graphUser[#"last_name"];
userInfo.userId = #([jsonObject[#"UserId"] intValue]);
userInfo.networkUserId = #([jsonObject[#"NetworkUserId"] longLongValue]);
userInfo.userPoint = #([jsonObject[#"PointsEarned"] floatValue]);
userInfo.imageUrl = jsonObject[#"Picturelist"][0][#"PictureUrL"];
userInfo.imageUrlArray = [NSKeyedArchiver archivedDataWithRootObject:jsonObject[#"Picturelist"]];
} completion:^(BOOL success, NSError *error) {
}];
Use this when your done
[[NSManagedObjectContext MR_defaultContext]saveToPersistentStoreAndWait];

Why is my app crashing on iPhone 4S because of Core Data request execute?

I have an app that works fine on the simulator 6.1, works fine on the iPhone5 and iPad3 on iOS6.1 but when run on iPhone4S it crashes in this method with Exc Bad Access:
-(void)parsePlistIntoCD{
self.managedObjectContext = [[SDCoreDataController sharedInstance] backgroundManagedObjectContext];
// 3: Now put the plistDictionary into CD...create get ManagedObjectContext
NSManagedObjectContext *context = self.managedObjectContext;
NSError *error;
//Create Request & set Entity for request
NSFetchRequest *holidayRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *topicEntityDescription = [NSEntityDescription entityForName:#"Holiday" inManagedObjectContext:context];
[holidayRequest setEntity:topicEntityDescription];
//Create new NSManagedObject
//Holiday *holidayObjectToSeed = nil;
Holiday *newHoliday = nil;
//Execute fetch just to make sure?
NSArray *holidayFetchedArray = [context executeFetchRequest:holidayRequest error:&error];
**if (error) NSLog(#"Error encountered in executing topic fetch request: %#", error); // if I comment this line out it reaches as far as the next bold line**
// No holidays in database so we proceed to populate the database
if ([holidayFetchedArray count] == 0) {
//Get path to plist file
NSString *holidaysPath = [[NSBundle mainBundle] pathForResource:#"PreloadedFarsiman" ofType:#"plist"];
//Put data into an array (with dictionaries in it)
NSArray *holidayDataArray = [[NSArray alloc] initWithContentsOfFile:holidaysPath];
**NSLog(#"holidayDataArray is %#", holidayDataArray);**
//Get number of items in that array
int numberOfTopics = [holidayDataArray count];
//Loop thru array items...
for (int i = 0; i<numberOfTopics; i++) {
//get each dict at each node
NSDictionary *holidayDataDictionary = [holidayDataArray objectAtIndex:i];
//Insert new object
newHoliday = [NSEntityDescription insertNewObjectForEntityForName:#"Holiday" inManagedObjectContext:context];
//Parse all keys in each dict object
[newHoliday setValuesForKeysWithDictionary:holidayDataDictionary];
//Save and or log error
[context save:&error];
if (error) NSLog(#"Error encountered in saving topic entity, %d, %#, Hint: check that the structure of the pList matches Core Data: %#",i, newHoliday, error);
};
}
//set bool that specifies the coredata has been populated from plist already
NSString *bundleVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
NSString *appFirstStartOfVersionKey = [NSString stringWithFormat:#"first_start_%#", bundleVersion];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#(YES) forKey:appFirstStartOfVersionKey];
[prefs synchronize];
}
Why only on 4S? It gives no console log and the last know method traversed in this one above. Here is a pic:
And as mentioned above, if I uncomment that NSLog line it reaches as far as logging the array, as shown in the pic. If I leave it in it stops at that line.
NSArray *holidayFetchedArray = [context executeFetchRequest:holidayRequest error:&error];
if (error)
NSLog(#"Error encountered in executing topic fetch request: %#", error);
No no no no no. I know this is a difficult pattern, but please let's try to do it right. Not if (error). error could be anything (esp. under non-ARC). The test is if (!holidayFetchedArray).
For all of these methods that return a value and also take an NSError** by indirection, you test the result to see if it is nil. If it is, then there was an error because returning nil is the sign that there was an error. Then and only then you may touch the error meaningfully.
The docs are always quite clear about this, though it is true that a fog can come over one's eyes at the critical instance, so I've added some comments in italic brackets to call out the key points:
request
A fetch request that specifies the search criteria for the
fetch.
error
If there is a problem executing the fetch, upon return
contains an instance of NSError that describes the problem.
[And if there is no problem executing the fetch, contains garbage so don't touch it!]
Return Value
An array of objects that meet the criteria specified by request
fetched from the receiver and from the persistent stores associated
with the receiver’s persistent store coordinator. If an error occurs,
returns nil. [And that, forsooth, is the sign that an error did occur.] If no objects match the criteria specified by request,
returns an empty array.
This might be the cause of your trouble or it might not, but you must fix it now. I want you to go through all your code looking for NSError* variables declared for use in this pattern and fix all of them! Thank you. Here endeth the lesson.
This is a stab in the dark b/c you haven't identified the line of code where the crash occurs. I recommended you set a breakpoint and then step through until you hit the crash. If what I say below doesn't resolve the issue then edit your post and add more info about where the crash occurs and we'll go from there.
Here's something to check. The line:
[newHoliday setValuesForKeysWithDictionary:holidayDataDictionary]
may be crashing if any of the keys in holidayDataDictionary aren't valid for an instance of the Holiday class.
With regard to your question about why it only crashes on your iPhone 4S there's not enough data to explain that yet. Depending on how you've been doing testing and core data migration (if at all) you may have a model inconsistency on that device, though I don't see anything in the screen shot you posted pointing me in that direction. I would try uninstalling/reinstalling your app and see if the crash is still iPhone 4S only.

Core Data NSValidation error 1620

I'm getting a "failed to save" error, no. 1620, when I try the following:
NSManagedObjectContext *context = [self managedObjectContext];
CustomObject *objToInsert = [NSEntityDescription insertNewObjectForEntityForName:#"CustomObject" inManagedObjectContext:context];
objToInsert.variable1 = [NSNumber numberWithFloat:10.0];
objToInsert.variable2 = [NSDate date];
objToInsert.variable3 = [NSNumber numberWithInt:1];
NSError *error;
if (![context save:&error]) {
NSLog(#"failed to save with error = %#", [error localizedDescription]);
}
This same logic works just fine when saving other NSManagedObject-subclass objects to the managedObjectContext. The 1620 error is listed as being a "number too small" validation error, but there's clearly nothing wrong with the numbers I'm inputting. The three variables are defined in my data model as Float, Date and Integer 16, though I'm not sure whether that's
relevant.
The Core Data stack is all present and correct and as I said, works just fine with other insertion logic. Am I missing something here?
EDIT: turns out from the error output that Core Data is trying to save a completely different NSManagedObject subclass, which I work with earlier in execution but not in this method call. Why would this be?
In the end, the solution was partly as suggested by Martin R (see comments) but for a completely different entity. It appears that if a required minimum value is set for any other entity in the data model, and that entity is modified and saved at some prior point, any subsequent saves to other entities will cause an error. This does not seem to be sensible - maybe I'm doing something wrong elsewhere? - but removing the minimum value requirement did solve this particular problem.

Resources