CoreData (storing new object) in AppDelegate = SIGABRT - iphone

I've intented to make a simple function in AppDelegate to store some data in database (CoreData) which would be called from various ViewController classes connected do AppDelegate. This is the body of this function:
- (void) setSetting:(NSString *)setting :(NSString *)value {
NSManagedObject* newSetting = [NSEntityDescription insertNewObjectForEntityForName:#"EntityName" inManagedObjectContext:self.managedObjectContext];
[newSetting setValue:value forKey:setting];
NSError* error;
[self.managedObjectContext save:&error];
}
But calling this function (even from AppDelegate itself) returns SIGABRT on line with setValue
But when I implement the function in ViewController class (replacing self. with proper connection to AppDelegate of course) - it works fine.
I don't get it and I would really appreciate some help in creating flexible function in AppDelegate to save the data in database.

This looks a bit like the key part is not an NSString or the value part is not the correct data type. Please check, and perhaps make the order of the arguments in your function the same as in the setValue:forKey method to avoid confusion.
Also, according to the documentation, an exception will be raised if the key is not defined in the model - so double-check your key strings.
BTW, if this is your error it is a good idea to move away from KVC and create your own NSManagedObject subclasses instead as a habit - makes life much easier.

The most likely explanation is that this line:
NSManagedObject* newSetting = [NSEntityDescription insertNewObjectForEntityForName:#"EntityName" inManagedObjectContext:self.managedObjectContext];
… returns a nil object either because the entity name is incorrect or because the managedObjectContext is itself nil or otherwise invalid.
Since the problem only occurs in the app delegate, I would first suspect some issue with self.managedObjectContext.

Related

Is there a way to instantiate a NSManagedObject without inserting it?

I have a user interface to insert a Transaction. once the user clicks on a plus he gets the screen and i want to instantiate my Core Data NSManagedObject entity let the user work on it. Then when the user clicks on the Save button i will call the save function.
so down to code:
transaction = (Transaction *)[NSEntityDescription insertNewObjectForEntityForName:#"Transaction" inManagedObjectContext:self.managedObjectContext];
//even if i dont call save: its going to show up on my table
[self.managedObjectContext save:&error]
P.S i am using an NSFetchedResultsController on that table and I see that the NSFetchedResultsController is inserting a section and an object to the table.
My thought is if there is a way to instantiate the Transaction NSManagedObject i could update it with out saving untill the client choses to.
For what it's worth, Marcus Zarra seems to be promoting the nil context approach, claiming that it's expensive to create a new context. For more details, see this answer to a similar question.
Update
I'm currently using the nil context approach and have encountered something that might be of interest to others. To create a managed object without a context, you use the initWithEntity:insertIntoManagedObjectContext: method of NSManagedObject. According to Apple's documentation for this method:
If context is not nil, this method
invokes [context insertObject:self]
(which causes awakeFromInsert to be
invoked).
The implication here is important. Using a nil context when creating a managed object will prevent insertObject: from being called and therefore prevent awakeFromInsert from being called. Consequently, any object initialization or setting of default property values done in awakeFromInsert will not happen automatically when using a nil context.
Bottom line: When using a managed object without a context, awakeFromInsert will not be called automatically and you may need extra code to compensate.
here is how i worked it out:
On load, where we know we are dealing with a new transaction, i created an out of context one.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Transaction" inManagedObjectContext:self.managedObjectContext];
transaction = (Transaction *)[[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
then when it came to establishing a relation ship i did this:
if( transaction.managedObjectContext == nil){
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Category" inManagedObjectContext:self.managedObjectContext];
Category *category = (Category *)[[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
category.title = ((Category *)obj).title;
transaction.category = category;
[category release];
}
else {
transaction.category = (Category *)obj;
}
and at the end to save:
if (transaction.managedObjectContext == nil) {
[self.managedObjectContext insertObject:transaction.category];
[self.managedObjectContext insertObject:transaction];
}
//NSLog(#"\n saving transaction\n%#", self.transaction);
NSError *error;
if (![self.managedObjectContext save:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
There's a fundamental problem with using a nil MOC: Objects in different MOCs aren't supposed to reference each other — this presumably also applies when one side of a relationship has a nil MOC. What happens if you save? (What happens when another part of your app saves?)
If your object doesn't have relationships, then there are plenty of things you can do (like NSCoding).
You might be able to use -[NSManagedObject isInserted] in NSPredicate (presumably it's YES between inserting and successfully saving). Alternatively, you can use a transient property with the same behaviour (set it to YES in awakeFromInsert and NO in willSave). Both of these may be problematic if a different part of your app saves.
Using a second MOC is how CoreData is "supposed" to be used, though; it handles conflict detection and resolution for you automatically. Of course, you don't want to create a new MOC each time there's a change; it might be vaguely sensible to have one MOC for unsaved changes by the slow "user thread" if you don't mind some parts of the UI seeing unsaved changes in other parts (the overhead of inter-MOC communication is negligible).
You can insert an NSManagedObjectContext with the -[NSManagedObject initWithEntity:insertIntoManagedObjectContext:], passing nil for the managed object context. You must, of course, assign it to a context (using -[NSManageObjectContext insertObject:] before saving. This is, as far as I know, not really the intended pattern in Core Data, however (but see #mzarra's answer here). There are some tricky ordering issues (i.e. making sure the instance gets assigned to a context before it expects to have one, etc.). The more standard pattern is to create a new managed object context and insert your new object into that context. When the user saves, save the context, and handle the NSManagedObjectDidSaveNotification to merge the changes into your 'main' context. If the user cancels the transaction, you just blow away the context and go on with your business.
An NSManagedObject can be created using the nil as the context, but if there other NSManagedObjects it must link to it will result in an error. The way I do it I pass the context into the destination screen and create a NSManagedObject in that screen. Make all the changes link other NSManagedObjects. If the user taps the cancel button I delete the NSManagedObject and save the context. If the user taps the the save button I update the data in the NSManagedObject, save it to the context, and release the screen. In the source screen I update the table with a reload.
Deleting the NSManagedObject in the destination screen gives core data time to update the file. This is usually enough time for you not to see the change in the tableview. In the iPhone Calendar app you have a delay from the time it saves to the time it shows up in the tableview. This could be considered a good thing from a UI stand point that your user will focus on the row that was just added. I hope this helps.
transaction = (Transaction *)[NSEntityDescription insertNewObjectForEntityForName:#"Transaction" inManagedObjectContext:nil];
if the last param is nil, it will return a NSManagedObject without save to db

how can I put all fetch requests in a Core Data DAL?

Totally new to Objective-C and Core Data, coming from a .net background I really want to put all of my fetch requests into some sort of class that I can call, preferably statically to get my objects, something like:
ObjectType *myObject = [CoreDataDAL GetObject:ID];
Anyone have a pattern to implement this?
I am hacking my way through one right now but it's probably not quite right, will post code when I have it.
EIDT:
Here is my code as it stands right now - seems to work great - please rip it part if I am going down the wrong road - here is the basic DAL:
#import "CoreDataDAL.h"
#import "CoreDataAppDelegate.h"
#implementation CoreDataDAL
#synthesize managedObjectContext;
-(id)init {
if (self=[super init]) {
CoreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
self.managedObjectContext = appDelegate.managedObjectContext;
}
return self;
}
-(Client *) GetClient:(NSString *) ClientID{
/* Client Fetch Request */
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entityType = [NSEntityDescription entityForName:#"Client" inManagedObjectContext:managedObjectContext];
[request setEntity:entityType];
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"ClientID==%#",ClientID];
[request setPredicate:predicate];
NSError *error;
NSArray *entities = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
return [entities objectAtIndex:0];
}
#end
And here is how it is used in my view controllers:
CoreDataDAL *dal = [[CoreDataDAL alloc]init];
Client *client = [dal GetClient:clientID];
[dal release];
Seems straight forward enough, thoughts?
Don't do this; what you're doing is porting a pattern from one context to another where it doesn't really make sense.
For one thing, you shouldn't be modeling IDs at all in Core Data; the framework does that for you with NSManagedObjectID already. Thus a -clientWithID: method on a CoreDataDAL class is redundant. (Note that I've also changed the name of your hypothetical method to follow proper Cocoa naming conventions.) Instead, you can just use -[NSManagedObjectContext objectWithID:] or -[NSManagedObjectContext existingObjectWithID:error:] to get an object based on its NSManagedObjectID.
Similarly, relationship management is handled for you. You don't need to have a method in your DAL that can (say) fetch all of the Address instances that apply for a given Client by evaluating some query. You can just traverse your Client's to-many addresses relationship to get at them, and manipulate the same relationship directly (rather than setting foreign keys etc.).
Finally, if you really do want to have methods to perform specialized queries, you can either specify the query via a fetched property on the appropriate entity for its results, or you can add that method directly to the appropriate class. Class methods in Objective-C aren't like static methods in C++, Java or C# - they can be overridden just as instance methods can, and are much more appropriate for this kind of use.
For example, say your Client entity has a syncID property representing the ID of the object that it represents in some web service. (Note that this is specifically for relating a local object to a remote object, not the "primary key" of the local object.) You'd probably have class methods on the MyClient class associated with your Client entity like this:
#implementation MyClient
+ (NSString *)entityClassName
{
return #"Client";
}
+ (NSEntityDescription *)entityInManagedObjectContext:(NSManagedObjectContext *)context
{
return [NSEntityDescription entityForName:[self entityClassName] inManagedObjectContext:context];
}
+ (MyClient *)clientWithSyncID:(NSString *)syncID
inManagedObjectContext:(NSManagedObjectContext *)context
error:(NSError **)error
{
MyClient *result = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[self entityInManagedObjectContext:context]];
[request setPredicate:[NSPredicate predicateWithFormat:#"syncID == %#", syncID]];
[request setFetchLimit:1];
NSArray *results = [context executeFetchRequest:request error:error];
if ([results count] > 0) {
result = [results objectAtIndex:0];
} else {
if (error != NULL) {
*error = [NSError errorWithDomain:MyAppErrorDomain
code:MyAppNoClientFoundError
userInfo:nil];
}
}
return result;
}
#end
This is similar to what you wrote in your DAL class, but instead of consolidating all of the fetches in one place, it puts the logic for fetches appropriate to a particular managed object class on that class, which is really where it belongs. Thanks to the fact Objective-C has true class methods, you can actually put methods like +entityInManagedObjectContext: and +entityClassName on a common base class and then override only the latter as appropriate in subclasses (or even have it generate an appropriate entity name from the class name).
To sum up:
Don't recreate what Core Data already implements for you in terms of things like object IDs, relationship management, and so on.
Leverage polymorphism at both the instance and the class level to keep your code clean, rather than use "utility" classes like "data access layers."
Fetch request properly belong to the individual controllers in the Model-View-Controller pattern. A fetch returns the specific information, in the specific order, required by each individual view. Each fetch is customized for the needs of each particular view. As such, putting all of an app's fetches in a single object would break encapsulation instead of enhancing it. Only fetched properties and fetched relationships belong in the data model itself.
The managed object context performs the function of the data object in simple apps. It implements all the functions necessary to get information in and out of the Core Data stack e.g. - objectWithID:. Much of the time, all you need to do is pass the context to controllers and let them configure fetches to it.
If your app is large or has multiple context, you can always wrap up the context/s in a custom manager class with various accessors and convenience methods to make the Core Data operations run more smoothly. You can legitimately and safely implement the manager class as a singleton to make accessing it everywhere in the app easy.
Edit:
The code looks okay except for the mutable copy. It's pointless and will leak memory. The entities array is only needed for one line and it's autorelease. The Client objects retention is managed by the context. You should test the error and at least log it for debugging.
You do want to avoid "get" and "set" for method names that are not accessors. The runtime looks methods that begin with "get" and "set" to find accessors. By convention, all method names start with lower case. You might want to make the method name more descriptive so that it auto-comments when you read it months down the road.
So:
[theCoreDataDal GetClient:vaugelyNamedString];
to
[theCoreDataDal clientWithClientID:vaugelyNamedString];
The problem your going to run into with trying to cram everything into one object is that the fetches are usually unique and configured for the needs of a specific interface.
Moreover, you usually start with a fetch to find specific objects but then you spend the rest of the time walking relationships based on input unknown until runtime.
Core Data is the data access layer. Most of the code you write for Core Data is actually controller code. There is nothing conceptually problematic about this GetClient method but how often are you going to execute this particular fetch?
When I create a Data Model Manager object, I use it largely to store boiler plate code. For example, while each fetch request is unique, they all start out the same with an entity description so I autogenerate methods to return the basic fetch for each entity and put that in the manager. Then I have another boiler plate method to actually perform the fetch. In use, a controller ask the manager for a fetch object for a specific entity. The controller customizes the fetch and then sends it back to the manager to perform the fetch and return the results.
Everything boiler plate is in the manager and everything customized is in the controller.

Leak in managedObjectContext save:

I have the following piece of code and when I use Instruments/Object Allocations, it tells me that there is a leak there (which goes down to sqlite3MemMalloc). Is there something that I should release?
if (![managedObjectContext save:&error]) {
NSLog(#"Error while saving.");
}
The save works well and doesn't trigger an error.
The leak is most likely in one of the managed objects being saved and it just shows here. If you look at the stack in Instruments you can probably see the leaking object. Since it only shows up at save, it's probably in validation code.
Do you have any subclasses of your NSManagedObject instances?
When you set a value into your NSManagedObject instances do you then release your ownership of them? For example if you were do to the following code:
NSString *someString = [[NSString alloc] initWithString:#"Blah"];
[myManagedObject setValue:someString forKey:#"stringValue"];
You would be leaking memory because you are still owning that NSString. That is what TechZen is referring to above.

Can I create an new instance of my custom managed object class without going through NSEntityDescription?

From an Apple example, I have this:
Event *event = (Event*)[NSEntityDescription
insertNewObjectForEntityForName:#"Event"
inManagedObjectContext:self.managedObjectContext];
Event inherits from NSManagedObject. Is there a way to avoid this weird call to NSEntityDescription and instead just alloc+init somehow directly the Event class? Would I have to write my own initializer that just does that stuff above? Or is NSManagedObject already intelligent enough to do that?
NSManagedObject provides a method called initWithEntity:insertIntoManagedObjectContext:. You can use this to do a more traditional alloc/init pair. Keep in mind that the object this returns is not autoreleased.
I've run into the exact same problem. It turns out you can completely create an entity and not add it to the store at first, then make some checks on it and if everything is good insert it into the store. I use it during an XML parsing session where I only want to insert entities once they have been properly and entirely parsed.
First you need to create the entity:
// This line creates the proper description using the managed context and entity name.
// Note that it uses the managed object context
NSEntityDescription *ent = [NSEntityDescription entityForName:#"Location" inManagedObjectContext:[self managedContext]];
// This line initialized the entity but does not insert it into the managed object context.
currentEntity = [[Location alloc] initWithEntity:ent insertIntoManagedObjectContext:nil];
Then once you are happy with the processing you can simply insert your entity into the store:
[self managedContext] insertObject:currentEntity
Note that in those examples the currentEntity object has been defined in a header file as follows:
id currentEntity
To get it to work properly, there is a LOT of stuff to do. -insertNewObject:... is by far the easiest way, weird or not. The documentation says:
A managed object differs from other
objects in three main ways—a managed
object ... Exists in an environment
defined by its managed object context
... there is therefore a lot of work
to do to create a new managed object
and properly integrate it into the
Core Data infrastructure ... you are
discouraged from overriding
initWithEntity:insertIntoManagedObjectContext:
That said, you can still do it (read further down the page to which I linked) but your goal appears to be "easier" or "less weird". I'd say the method you feel is weird is actually the simplest, most normal way.
I found a definitive answer from More iPhone 3 Development by Dave Mark and Jeff LeMarche.
If it really bothers you that you use a method on NSEntityDescrpiton rather than on NSManagedObjectContext to insert a new object into an NSManagedObjectContext, you can use a category to add an instance method to NSManagedObjectContext.
Create two new text files called NSManagedObject-Insert.h and NSManagedObject-Insert.m.
In NSManagedObject-Insert.h, place the following code:
import <Cocoa/Cocoa.h>
#interface NSManagedObjectContext (insert)
- (NSManagedObject *)insertNewEntityWithName:(NSString *)name;
#end
In NSManagedObject-Insert.m, place this code:
#import "NSManagedObjectContext-insert.h"
#implementation NSManagedObjectContext (insert)
- (NSManagedObject *)insertNewEntityWithName:(NSString *)name
{
return [NSEntityDescription insertNewObjectForEntityForName:name inManagedObjectContext:self];
}
#end
You can import NSManagedObject-Insert.h anywhere you wish to use this new method. Then replace the insert calls against NSEntityDescription, like this one:
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
with the shorter and more intuitive one:
[context insertNewEntityWithName:[entity name]];
Aren't categories grand?

Iphone Core Data Internal Inconsistency

This question has something to do with the question I posted here: Iphone Core Data crashing on Save
however the error is different so I am making a new question. Now I get this error when trying to insert new objects into my managedObjectContext:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: '"MailMessage" is not a subclass of NSManagedObject.'
But clearly it is:
#interface MailMessage : NSManagedObject { ....
And when I run this code:
NSManagedObjectModel *managedObjectModel = [[self.managedObjectContext
persistentStoreCoordinator] managedObjectModel];
NSEntityDescription *entity =[[managedObjectModel entitiesByName]
objectForKey:#"MailMessage"];
NSManagedObject *newObject = [[NSManagedObject alloc] initWithEntity:entity
insertIntoManagedObjectContext:self.managedObjectContext];
It runs fine when I do not present an MFMailComposeViewController, but if I run this code in the
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
method, it throws the above error when creating the newObject variable.
The entity object when I use print object produces the following:
(<NSEntityDescription: 0x1202e0>) name MailMessage, managedObjectClassName MailMessage,
renamingIdentifier MailMessage, isAbstract 0, superentity name (null), properties {
in both cases, so I don't think the managedObjectContext is completely invalid. I have no idea why it would say MailMessage is not a subclass of NSManagedObject at that point, and not at the other.
Any help would be appreciated, thanks in advance.
Class MailMessage could be implemented in a library or somewhere else in the framework. As Objective C does not implement namespaces, one of the two will be used. Which one is undefined. Try giving your class a different name to quickly resolve the issue.
Look for a message like this from the debugger. It will confirm what Benjamin says.
Class MailMesssage is implemented in both /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/System/Library/PrivateFrameworks/Message.framework/Message and /Users/home/Library/Application Support/iPhone Simulator/4.2/Applications/FFFFFFFF-FFFF-0000-0000-AAAAAAAAAAA/Projects.app/Projects. One of the two will be used. Which one is undefined.
Try resetting the Simulator or uninstalling the application from your device. Often the NSInternalInconsistencyException has to do with problems with changing the datamodel and the database not being updated accordingly.
I was able to workaround this by creating the MailMessage object before presenting the modal view controller. Once the MailMessage object was already created, saving changes did not present a problem. A strange workaround and not addressing the actual problem as far as I know, but it works.