Get changed objects in NSManagedObjectContext before saving? - rest

I want to save changes on backend also, so I want to subclass NSManagedContext, override save method and loop al the changed object and call the appropriate RESTFull service. But how can I get the changed / inserted objects?
UPDATE:
I found that with setIncludesPendingChanges I can get the changed objects, but I still need to set the entity name for NSFetchRequest. But I want to fetch all different type of entites. How?

I found here a more appropriate solution based on NSManagedObjectContextDidSaveNotification: How to sync CoreData and a REST web service asynchronously and the same time properly propagate any REST errors into the UI

Related

asp.net mvc accessing class fields from a custom auth attribute

I am using a custom AuthAttribute to determine whether a user can access a controller and/or actions. The problem is I have to duplicate information and EFx connections in the attribute that already exist on the class that is being adorned.
My question is whether there is a way to access the fields on the adorned class from the custom AuthAttribute? I am trying to avoid having to re-architect the software in a way that would provide a single point of access since that would open up a different can of worms.
I believe I have found an answer that works. I welcome all comments on this solution.
Rather than have the attribute gain access to the properties and fields on the controller it adorns you can share values between them in a thread-safe way through the common HttpContext object. So if you are being extreme like I am and are trying to cut down on duplicate calls to your database in both the authattribute and the adorned controller action then pass the results forward. What that means is the authattribute will be called first and you can stash the retrieved values in the "Items" collection off the HttpContext object passed into the AuthorizeCore(..) method. You can then retrieve the same value in a THREAD-SAFE way through the HttpContext object in the controller.
example to save value within the AuthorizeCore(..) override of the AuthAttribute:
httpContext.Items.Add("fester", "bester");
example to retrieve value inside the subsequent call to the Controller/Action:
this.HttpContext.ApplicationInstance.Context.Items["fester"];
I have to warn you this is only a possible implementation that appears to work in simple testing. Personally it feels like a hack and there has to be a better way. I would also state this is in pursuit of a dubious performance benefit. It should cut down on the number of database and/or network calls by cache'ing retrieved data in the HttpContext so you don't have to repeat the calls in both the authattribute and the adorned Controller/Action. If you don't have a web site that gets a huge volume of calls then I would warn you against this.
I hope someone recommends something better on this page. I will keep an eye on how this works on my web site and let y'all know if it behaves and is truly thread-safe.

Can I make instances of an NSManagedObject in no particular NSManagedObjectContext?

I'm building an app which receives a number of listings from a web API, and allows the user to save some for offline viewing. My usual approach would be:
Get the data from the API, and make a new Listing object for each datum
Save the object to the DB if the user chooses to do so.
But this is a Core Data app, so the context is what gets saved, not the object. Under those circumstances, the above would become something like this:
Get the data from the API, and make an unmanaged Listing object for each datum
Move the object into the managed context if the user chooses to do so, then save the context
One approach to having an unmanaged and a managed version of Listing objects would be to have two classes, e.g. ManagedListing and UnmanagedListing - but that's a horribly repetitive way of doing it.
What I'd like is to make Listing a subclass of NSManagedObject; initialise a bunch of them without an NSManagedObjectContext; then when I want to save one, I either set its context or I copy its attributes to a new Listing inside a context.
Can I make instances of an NSManagedObject in no particular NSManagedObjectContext? If so, how?
Use two persistent stores, one in memory and one on disk. If the user wants to save, move the object to the other store using assignObject:toPersistentStore:.
In iOS < 5.0 - yes.
In iOS >= 5.0 - no.

EF Code First DBContext Lifetime for web applications

we are developing ASP.NET web application with cEF ode first. What/Where is the best possible place to create/dispose DBContext for a request? I have only a single context and am not using any DI containers. Currently i have multiple methods to call per request and each creates context of their own. How do i say, something like.. GetContextforRequest() and use it for the request and dispose it when request is processed?
Thanks in advance
What't your looking for in terms of having 1 context per request is a pretty good way to use contexts, in that you reduce the overhead of creating them. You can create new context on BeginRequest, and store it in HttpContext.Current.Items, and on EndRequest dispose of it.
You can then create a . GetContextforRequest() method to encapsulate the fetch from HttpContext.Current.Items
I would however suggest looking at using a DI container. most of them have helpers to aide with creating and disposing of objects per request.
Edit
The benefit of having a Context open for the duration of a Request is that you can take advantage of 1st level caching. This is where objects are cached for the lifetime of the Context. So say you have a table called User containing a bunch of Users, and you call context.Set().ToList() twice in the same request, the first call will fetch the data from the database, the second call will retrieve it from the 1st level cache.

Should I have all my web service code in my view controller

I have noticed that with iPhone programming you kind of need to retrieve your data from within the ViewController because of the way the data is retrieved.
e.g.: ViewDidLoad is called. You start retrieving the data and then when its finished a message is sent to your viewcontroller e.g. requestFinished and this is where you configure/refresh your UI.
The problem that I have with this approach is that I have a bunch of web service code and XML building and parsing all in my view controller.
Does anyone know if this is the correct approach or is there a better way to do this.
In .NET I would have classes specifically for retrieving data from webservices and I would simply call the web service to fetch the data and I could use the same web service at various places inside my app.
There is no reason to do that different in Objective-C/Cocoa. You should create a class that handles the web service and notifies the view controller when data is available.
No, it absolutely isn't the correct approach. The key to this is the MVC paradigm, - model, view, controller - your data classes are perfectly suited to being the M = model so put all your data handling code inside a dedicated model class.
Because the url handling is hopefully asynchronous, your model will still need to inform your view controller when various events have taken place. You have a couple of choices here but the most appropriate is probably to use a delegate pattern so that the model can basically initiate a call back to the view controller when it has data that needs displaying etc.
(The other approach would be to use notifications which is less tightly coupled, and perfectly viable in this scenario, but delegates would be more appropriate).
Well you could create a parse that will parse your XML in a seprate class, and even your http request can be in a seprate class.
There is no need to do every thing in the the on viewcontroller.
Just be sure to create delegate or use the notification center if you are using threads. Set the delegate on either the request or parse to nil if the view controller get unloaded.

Am I using Core Data properly by fetching an object once at startup and calling save when I want to persist the data?

I'm diving into iOS programming and am using Core Data in my app to persist the game data, however, I'm wondering if my approach is the wrong way to use Core Data. I have three tables in my DB, with the first two having a one-to-many relationship with the another table (i.e. UserProfile -->> Puzzle Packs -->> Puzzles).
The approach I'm taking to use and persist the data is simple, retrieve an instance of a UserProfile using a NSFetchedResultsController and store the UserProfile object as an instance var in my App Delegate. Then I use that UserProfile object throughout the rest of the code to access and modify the state of the puzzle packs and puzzles (representing the user's progress in the game) and whenever I make a change to the objects, I just call the NSManagedObjectContext's save method to update the DB, which is is also stored in the App Delegate.
My question is, should I be fetching data from the DB anytime I need to access or modify it or is my current approach, of fetching the top object once and calling the save method often, the correct way to use Core Data?
Thanks in advance for your wisdom! I apologize if my question is odd, I'm still a noob.
As long as you're only ever working with these objects with a single NSManagedObjectContext (ie, you never have to merge changes between contexts) then I don't see a problem with fetching once, and saving as needed.
That said, the moment you work with multiple contexts (for example, using NSOperation/NSOperationQueue or other multi-threading techniques, which require separate contexts), you'll want to make sure you merge changes and update other contexts so changes from one thread don't clobber something on another.