Core Data relationship not saved to store - iphone

I've got this command line app that iterates through CSV files to create a Core Data SQLite store. At some point I'm building these SPStop objects, which has routes and schedules to-many relationships:
SPRoute *route = (SPRoute*)[self.idTransformer objectForOldID:routeID ofType:#"routes" onContext:self.coreDataController.managedObjectContext];
SPStop *stopObject = (SPStop*)[self.idTransformer objectForOldID:stopID ofType:#"stops" onContext:self.coreDataController.managedObjectContext];
[stopObject addSchedulesObject:scheduleObject];
[stopObject addRoutesObject:route];
[self.coreDataController saveMOC];
If I log my stopObject object (before or after saving; same result), I get the following:
latitude = "45.50909";
longitude = "-73.80914";
name = "Roxboro-Pierrefonds";
routes = (
"0x10480b1b0 <x-coredata://A7B68C47-3F73-4B7E-9971-2B2CC42DB56E/SPRoute/p2>"
);
schedules = (
"0x104833c60 <x-coredata:///SPSchedule/tB5BCE5DC-1B08-4D11-BCBB-82CD9AC42AFF131>"
);
Notice how the routes and schedules object URL formats differ? This must be for a reason, because further down the road when I use the sqlite store and print the same stopObject, my routes set is empty, but the schedules one isn't.
I realize this is very little debugging information but maybe the different URL formats rings a bell for someone? What could I be doing wrong that would cause this?
EDIT: it seems that one SPRoute object can only be assigned to one SPStop at once. I inserted breakpoints at the end of the iteration and had a look a the sqlite every time and I definitely see that as soon as an SPRoute object (that already had been assigned to a previous stop.routes) is assigned to a new SPStop, the previous stop.routes set gets emptied. How can this be?

Well, we had disabled Xcode's inverse relationship's warning which clearly states:
SPStop.routes does not have an inverse; this is an advanced
setting (no object can be in multiple destinations for a specific
relationship)
Which was precisely our issue. We had ditched inverse relationships because Apple states that they're only good for "data integrity". Our store is read-only so we figured we didn't really need them. We learn now that inverse relationships are a little more than just for "data integrity" :P

Related

Saving a score to firebase with attached values

What I'm wanting to accomplish is save a score to firebase that has two values attached to it. Here's the code that writes the score to firebase.
func writeToFirebase() {
DispatchQueue.global(qos: .userInteractive).async {
self.ref = Database.database().reference()
if GameManager.instance.getTopScores().contains(GameManager.instance.getGameScore()) {
self.ref?.child("user")
.child(GameManager.instance.getUsername())
.child(String(GameManager.instance.getGameScore()))
.updateChildValues( [
"badge":GameManager.instance.getBadgeLevel(),
"vehicle": GameManager.instance.getVehicleSelected()
]
)
}
}
}
The issue I'm having is when a new score is saved with its values it sometimes overwrites the other scores. This seems to be random and its not when they're the same score or anything like that. Sometimes it will only overwrite one score and sometimes multiple. I'm watching firebase and I can see it being overwritten, it turns red and then is deleted. Sometimes the new score being added will be red and get deleted. The score doesn't need to be a child, but I don't know how to attach values to it if it's not. Any help is appreciated
This issue seems to happen occasionally so I am going to post my comment as an answer.
There are situations where an observer may be added to a node and when data changes in that node, like a write or update, it will fire that observer which may then overwrite the existing data with nil.
You can see this visually in the console as when the write occurs, you can see the data change/update, then it turns red and then mysteriously vanishes.
As suggested in my comment, add a breakpoint to the function that performs the write and run the code. See if that function is called twice (or more). If that's the case, the first write is storing the data properly but upon calling it a second time, the values being written are probably nil, which then makes the node 'go away' as Firebase nodes cannot exist without a value.
Generally speaking if you see your data turn red and vanish, it's likely caused by nil values being written to the node.

Moving from file-based tracing session to real time session

I need to log trace events during boot so I configure an AutoLogger with all the required providers. But when my service/process starts I want to switch to real-time mode so that the file doesn't explode.
I'm using TraceEvent and I can't figure out how to do this move correctly and atomically.
The first thing I tried:
const int timeToWait = 5000;
using (var tes = new TraceEventSession("TEMPSESSIONNAME", #"c:\temp\TEMPSESSIONNAME.etl") { StopOnDispose = false })
{
tes.EnableProvider(ProviderExtensions.ProviderName<MicrosoftWindowsKernelProcess>());
Thread.Sleep(timeToWait);
}
using (var tes = new TraceEventSession("TEMPSESSIONNAME", TraceEventSessionOptions.Attach))
{
Thread.Sleep(timeToWait);
tes.SetFileName(null);
Thread.Sleep(timeToWait);
Console.WriteLine("Done");
}
Here I wanted to make that I can transfer the session to real-time mode. But instead, the file I got contained events from a 15s period instead of just 10s.
The same happens if I use new TraceEventSession("TEMPSESSIONNAME", #"c:\temp\TEMPSESSIONNAME.etl", TraceEventSessionOptions.Create) instead.
It seems that the following will cause the file to stop being written to:
using (var tes = new TraceEventSession("TEMPSESSIONNAME"))
{
tes.EnableProvider(ProviderExtensions.ProviderName<MicrosoftWindowsKernelProcess>());
Thread.Sleep(timeToWait);
}
But here I must reenable all the providers and according to the documentation "if the session already existed it is closed and reopened (thus orphans are cleaned up on next use)". I don't understand the last part about orphans. Obviously some events might occur in the time between closing, opening and subscribing on the events. Does this mean I will lose these events or will I get the later?
I also found the following in the documentation of the library:
In real time mode, events are buffered and there is at least a second or so delay (typically 3 sec) between the firing of the event and the reception by the session (to allow events to be delivered in efficient clumps of many events)
Does this make the above code alright (well, unless the improbable happens and for some reason my thread is delayed for more than a second between creating the real-time session and starting processing the events)?
I could close the session and create a new different one but then I think I'd miss some events. Or I could open a new session and then close the file-based one but then I might get duplicate events.
I couldn't find online any examples of moving from a file-based trace to a real-time trace.
I managed to contact the author of TraceEvent and this is the answer I got:
Re the exception of the 'auto-closing and restarting' feature, it is really questions about the OS (TraceEvent simply calls the underlying OS API). Just FYI, the deal about orphans is that it is EASY for your process to exit but leave a session going. This MAY be what you want, but often it is not, and so to make the common case 'just work' if you do Create (which is the default), it will close a session if it already existed (since you asked for a new one).
Experimentation of course is the touchstone of 'truth' but I would frankly expecting unusual combinations to just work is generally NOT true.
My recommendation is to keep it simple. You need to open a new session and close the original one. Yes, you will end up with duplicates, but you CAN filter them out (after all they are IDENTICAL timestamps).
The other possibility is use SetFileName in its intended way (from one file to another). This certainly solves your problem of file size growth, and often is a good way to deal with other scenarios (after all you can start up you processing and start deleting files even as new files are being generated).

Really simple CoreData relationship but returns nil and null?

This bug has been busting me for the past 4 hours.
Also when I swap it round and get the User data first then Message data... the User.name will show, but the Message.message will not. So the data is definitely going in but the relationship between them seems to be broken.
Firstly, +1 for the effort with the image you created to illustrate your problem.
The cause of your issue is that you never assigned the user to the message (or vice-versa).
Try
message.fetchUser = user;
or
user.fetchMessage = message;
Then save your context and perform the fetch request.
As Rog said, I needed to assign the user to the message (or vice vera). Basically I placed this bit of code after where its entering the data.
messageDetails.fetchUser = userDetails

Undo core data managed object

I have this code:
Store* store = [NSEntityDescription insertNewObjectForEntityForName:#"Store"];
store.name = #"My Company"
...
Now the store is managed in the context and will be saved when the context is saved, but I have a button where the user can cancel the form where data is collected. How do I undo or remove this from the context? Or am I thinking wrong?
Core Data has built-in support for undo, so you can undo individual changes by sending the -undo message to the context:
[store.managedObjectContext undo];
It also supports -redo. You can undo all changes up to the most recent save using the -rollback method:
[store.managedObjectContext rollback]
as indicated in #melsam's answer.
As mentioned earlier, you can use an undo manager. Or, you could simply use a separate ManagedObjectContext, and do all your changes in there. If you decide to keep them, save the context. If not, simply discard it. A MOC is just a scratch pad for work, and has no impact on the underlying database until saved.
You can't really "detach an entity" but you can cause a managed object to turn back into a fault, losing any changes that have not been saved.
[managedObjectContext refreshObject:object mergeChanges:NO];
Snipped from the documentation...
If flag is NO, then object is turned into a fault and any pending
changes are lost. The object remains a fault until it is accessed
again, at which time its property values will be reloaded from the
store or last cached state.
[store.managedObjectContext rollback];
Undo works only when I create a undoManager(Swift 5):
managedObjectContext.undoManager = UndoManager()
After this configuration you can undo a last change:
managedObjectContext.undo()
Also you could save all data from the user in an array and when the user is ready, you only have to save the array to core data.

Proper Management Of A Singleton Data Store In IOS With Web Service

I'm currently using a singleton as a data store for my app. I essentially store a number of events that are pulled and parsed from a web service and then added as needed. Each time I make a request from the web service, I parse the results and see if the items already exist. If they do, I delete them and add the updated version provided by the web service.
Everything appeared to be working properly until I fired up the Instruments panel to find out that my system is leaking the objects every time it loads them from the web service (from the second time on). The core method where things appear to be messing up is this one, which is located in my HollerStore singleton class:
- (void)addHoller: (Holler *)h
{
//Take a holler, check to see if one like it already exists
int i = 0;
NSArray *theHollers = [NSArray arrayWithArray:allHollers];
for( Holler *th in theHollers )
{
if( [[th hollerId]isEqualToString:[h hollerId]] )
{
NSLog(#"Removing holler at index %i", i);
[allHollers removeObjectAtIndex:i];
}
i++;
}
[allHollers addObject:h];
}
Quick explanation: I decided to copy the allHollers NSMutableArray into theHollers because it's being updated asynchronously by NSURLConnection. If I update it directly, it results in a crash. As such, I switched to this model hoping to solve the problem, however the Instruments panel is telling me that my objects are leaking. All the counts are exactly the # of items I have in my data set.
From what I can tell removeObjectAtIndex isn't effectively removing the items. Would love to get the thoughts of anybody else out there on three things:
Is my analysis correct that something else must be retaining the individual hollers being added?
Should I be using CoreData or SQLite for storing information pulled from the web service?
Do you know how long data stored in a Singleton should be available for? Until the app is killed?
Update
I think I've found the source, however perhaps someone can provide some clarity on the proper way to do this. I've created a method called parseHoller which takes a dictionary object created through SBJSON and returns my own model (Holler). Here are the last couple lines:
Holler *h = [[[Holler alloc] initFromApiResponse:hollerId
creatorId:creatorId
creatorName:creatorName
creatorImageUrl:creatorImage
comments:comments
attendees:attendees
wishes:wishes
invitees:invites
createdAt:createdAt
text:text
title:title
when:when]autorelease];
//(some other autorelease stuff is here to clean up the internal method)
return h;
I figured that since I'm returning an autoreleased object, this should be fine. Do you see anything wrong with this?
Have you tried to do a retain count on the objects that is leaking? Maybe that could clear up when or where it is being retained.
The code should be
[putObjectHere retainCount];
and then write to an NSLog
Hope it gives you something
Peter