ObjC Realm Threading issue - objective-c

I have a Realm object (LFEMemory) which has a publish method.
When I call the publish method, I have to upload an image to AWS and then update the object with the URL returned by Amazon.
The problem is that when the block returns from AWS, my self LFEMemory object is no longer thread-safe. (In fact, it usually is during the usual running of the app but never if I'm using an App Extension).
I could fix this by removing the publish method from the realm object, and handling it in a controller object, which can fetch a new realm object on the new thread. But that means I need to create new realms everytime I call a block, which surely isn't a good practise.
How do most people handle this situation?
- (void)publishWithBlock:(ResultBlock)block {
FileUploadManager *manager = [[FileUploadManager alloc] init];
[manager uploadWithSuccess:^(NSString *filename) {
//self is no longer thread-safe and will cause a crash
self.media.path = filename;
} failure:^(NSError *error) {
block(NO, error);
};
}

You have various options you can explore:
1) if your object has a primary key (string or a number) you can store the id as a constant inside the method and use it to fetch back the object from any thread by using [Realm objectOfType:forPrimaryKey:]. docs
Don't be afraid to get a new realm from the different thread if that's what you need to do - that does not create "another" Realm or duplicate your file.
2) if you don't have a primary key you can simply create self.media on the main thread and whenever the upload has finished, switch again to the main queue and modify your object there - modifying a property or two on a Realm object will not harm at all your performance on the main thread.
Further - if you have access to your object (as in self.media) it already gives you access to the original Realm used to create / read the object via its realm property docs
Still - I'd go with using the primary key of the object to re-fetch a reference to the object I need if in doubt.

Related

WidgetKit not calling urlSessionDidFinishEvents

I'm trying to implement downloading timeline data in a widget and so I created a background URLSession with a corresponding data task to download the JSON:
let session = URLSession(
configuration: .background(withIdentifier: identifier),
delegate: self,
delegateQueue: nil
)
let request = URLRequest(url: ...)
session.dataTask(with: request).resume()
On my widget I then added the onBackgroundURLSessionEvents to store the completion handler, as per the Apple docs:
.onBackgroundURLSessionEvents { identifier in
return SessionCache.shared.isValid(for: identifier)
} _: { identifier, completion in
let data = SessionCache.shared.sessionData(for: identifier)
data.sessionCompletion = completion
}
However, neither the urlSessionDidFinishEvents(forBackgroundURLSession:) nor the onBackgroundURLSessionEvents methods are called. When the network download completes, it just calls the normal urlSession(_:task:didCompleteWithError:) method.
I'm clearly missing something here, but I'm just not seeing what.
Apple's documentation isn't 100% clear on this, but you need to use URLSession.downloadTask instead of dataTask for background sessions. URLSessionDataTasks deliver bytes to those specific delegate methods in your in-memory process. Background download & upload tasks are handed off to nsurlsessiond and only delivered back to your app when they are fully resolved.

Save LinkedList to Parse Server

I'm trying to build a Single Linked List using Parse PFObjects. Each PFObject has a pointer to the next object in the list. I can pin them locally, but I'm having an issue when saving them to Parse Server.
The problem start here:
+ (BFTask *)_deepSaveAsyncChildrenOfObject:(id)object withCurrentUser:(PFUser *)currentUser sessionToken:(NSString *)sessionToken;
// This saves all of the objects and files reachable from the given object.
// It does its work in multiple waves, saving as many as possible in each wave.
// If there's ever an error, it just gives up, sets error, and returns NO;
When trying to save the first object in the list, it will access the child (next object) and try to save that one first. As the child (next object) has also a pointer to the next object in list, this will keep happening until the last object in the list.
This succeeds for small amount of objects (<200) but once we are handling linked list with large amounts of objects, there is a crash in here:
/**
Finds all of the objects that are reachable from child, including child itself,
and adds them to the given mutable array. It traverses arrays and json objects.
#param node An kind object to search for children.
#param dirtyChildren The array to collect the result into.
#param seen The set of all objects that have already been seen.
#param seenNew The set of new objects that have already been seen since the
last existing object.
*/
+ (BOOL)collectDirtyChildren:(id)node
children:(NSMutableSet *)dirtyChildren
files:(NSMutableSet *)dirtyFiles
seen:(NSSet *)seen
seenNew:(NSSet *)seenNew
currentUser:(PFUser *)currentUser
error:(NSError * __autoreleasing *)error
This method is called by deepSaveAsyncChildrenOfObject to build a NSSet of the children objects that must be saved too.
#synchronized ([object lock]) {
// Check for cycles of new objects. Any such cycle means it will be
// impossible to save this collection of objects, so throw an exception.
if (object.objectId) {
seenNew = [NSSet set];
} else {
if ([seenNew containsObject:object] && error) {
*error = [PFErrorUtilities errorWithCode:kPFErrorInvalidPointer
message:#"Found a circular dependency when saving."];
return NO;
}
// 🚨CRASH: Thread 160: EXC_BAD_ACCESS (code=2, address=0x70000fc80f38)
seenNew = [seenNew setByAddingObject:object];
}
// Check for cycles of any object. If this occurs, then there's no
// problem, but we shouldn't recurse any deeper, because it would be
// an infinite recursion.
if ([seen containsObject:object]) {
return YES;
}
seen = [seen setByAddingObject:object];
// Recurse into this object's children looking for dirty children.
// We only need to look at the child object's current estimated data,
// because that's the only data that might need to be saved now.
toSearch = [object._estimatedData.dictionaryRepresentation copy];
}
So, this could be avoided by saving the PFObjects without saving its children, is there any way to do this? Or is there any workaround to save linked lists to Parse Server, maybe by using Cloud Code, or modifying the data model?

Creating Lua globals in Objective C/C from userdata

I am working on a library to allow Lua (5.2) scripting of games in iOS 5.x. I have created a class and added bindings to allow it to be created and accessed form Lua. The C initializer method called from Lua is given below:
static int newGeminiObject(lua_State *L){
GeminiObject *go = [[GeminiObject alloc] initWithLuaState:L];
GeminiObject **lgo = (GeminiObject **)lua_newuserdata(L, sizeof(GeminiObject *));
*lgo = go;
luaL_getmetatable(L, GEMINI_OBJECT_LUA_KEY);
lua_setmetatable(L, -2);
lua_newtable(L);
lua_setuservalue(L, -2);
NSLog(#"New GeminiObject created");
// add this new object to the globall list of objects
[[Gemini shared].geminiObjects addObject:go];
return 1;
}
This assigns a metatable which is set up elsewhere to provide access to various methods. Additionally, it attaches a table as a uservalue to allow script code to assign attributes to the objects.
I can create these objects in Lua scripts with no problem:
require "gemini"
x = gemini.new()
x:addEventListener("touch", objectTouched)
Here objectTouched is a a Lua method defined elsewhere that handles a touch event. Here addEventListener binds it to touch events.
These objects work just fine. When I attempt to create one from C, however, I am running into problems. I can create the object, but trying to assign it to a global and then invoke it in a script fails.
The following C code runs
-(void) addRuntimeObject {
GeminiObject *rt = [[GeminiObject alloc] initWithLuaState:L];
GeminiObject **lruntime = (GeminiObject **)lua_newuserdata(L, sizeof(GeminiObject *));
*lruntime = rt;
// set the metatable - effectively declaring the type for this object
luaL_getmetatable(L, GEMINI_OBJECT_LUA_KEY);
lua_setmetatable(L, -2);
// add a table to hold anything the user wants to add
lua_newtable(L);
lua_setuservalue(L, -2);
// create an entry in the global table
lua_setglobal(L, "Runtime");
// empty the stack
lua_pop(L, lua_gettop(L));
}
This should define a global named "Runtime". Trying to access this variable from a script like this
Runtime:addEventListener("enterFrame", enterFrame)
Results in the following error:
attempt to index global 'Runtime' (a userdata value)
It is a userdata value, but this doesn't seem to matter when I create one in Lua directly. The metatable binding provides access to the methods and metamethods. Again, this works fine if the object is created from Lua, just not when it is created in C.
Any ideas as to what I'm doing wrong here, or what the correct way to make a global from userdata is?
EDIT
Based on comments below regarding confusion about GEMINI_OBJECT_LUA_KEY, I thought I would list the code that is actually used in the binding:
static const struct luaL_Reg geminiObjectLib_f [] = {
{"new", newGeminiObject},
{NULL, NULL}
};
static const struct luaL_Reg geminiObjectLib_m [] = {
{"addEventListener", addEventListener},
{"__gc", geminiObjectGC},
{"__index", l_irc_index},
{"__newindex", l_irc_newindex},
{NULL, NULL}
};
int luaopen_geminiObjectLib (lua_State *L){
// create the metatable and put it into the registry
luaL_newmetatable(L, GEMINI_OBJECT_LUA_KEY);
lua_pushvalue(L, -1); // duplicates the metatable
luaL_setfuncs(L, geminiObjectLib_m, 0);
// create a table/library to hold the functions
luaL_newlib(L, geminiObjectLib_f);
NSLog(#"gemini lib opened");
return 1;
}
This code registers the library of functions (not show here) that provide the methods and metamethods for the GeminiObjects. The call to luaL_newmetatable creates a new metatable and associates it in the registry with the key GEMINI_OBJECT_LUA_KEY. GEMINI_OBJECT_LUA_KEY is just a unique string defined in the header. luaL_setfuncs actually adds the function pointers to the metatable, making them available as methods of the objects.
In case anyone is still interested, I got the answer to my question from the kind folks on the Lua mailing list. The problem here is that the library binding function luaopen_geminiObjectLib is not called before my call to addRuntimeObject.
Since iOS does not support dynamic libraries, I had added my libraries in statically by adding pointers to them to the preloadedlibs array in linit.c of the Lua source. Unfortunately, libraries added this way are not loaded until require('libname') is executed in a Lua script. Since I was calling my addRuntimeObject method prior to executing the Lua script, the library was not yet loaded.
The solution is to add the pointer to luaopen_geminiObjectLib to the loadedlibs array in the same linit.c file. This causes the library to be loaded when Lua starts up with no need for scripts to require it.

How is it better to wait an asynchronous method to be finished in iPhone app?

everybody.
I want to understand, how i shoud procceed situations when an asynchronous method has "didFinish:#selector(SEL)" parameter.
My code example is:
//
// Authentication check
- ( void )authenticationSuccess: ( GDataServiceTicket* ) ticket
authenticatedWithError: ( NSError* ) error {
if ( error == nil )
{
NSLog( #"authentication success" );
}
else
{
NSLog( #"authentication error" );
}
}
//
- ( void ) fetchFeedOfSpreadsheets {
//create and authenticate to a google spreadsheet service
if ( !(mService) )
{
GDataServiceGoogleSpreadsheet *service = [self spreadsheetService];
[mService autorelease];
mService = [service retain];
}
// check autentication success ( invoke "authenticationSuccess" method for debug success & error )
[mService authenticateWithDelegate: self
didAuthenticateSelector:#selector(authenticationSuccess:
authenticatedWithError:) ];
// HERE I WANT TO MAKE A PAUSE AND WHAIT THE RESULT, EITHER I AUTHENTICATED OR NOT
// AND MAKE AN "IF" STATEMENT TO CONTINTUE WORKING ON SERVER, OR RETURN ERROR
//fetch retrieves the feed of spreadsheets entries
NSURL *feedURL = [ NSURL URLWithString: kGDataGoogleSpreadsheetsPrivateFullFeed ];
GDataServiceTicket *ticket;
ticket = [mService fetchFeedWithURL: feedURL
delegate: self
didFinishSelector: #selector(spreadsheetsTicket:finishedWithFeed:
error: ) ];
// HERE I WANT TO WAIT SECOND TIME. I WANT "spreadsheetsTicket:
// finishedWithFeed:error:" TO PROCCEED ERROR AND PUT A FEED IN SOME NSARRAY OBJECT
// AND AFTER THAT I WANT TO WORK WITH THAT NSARRAY RIGHT HERE
}
I's clear, that i can push the code i want into the end of "authenticationSuccess" method section, but it's also clear, that it's a wrong a way to solve the proble. There a number of situations like this, where i call an asynchronous method with a selector parameter, and i want to find a solution providing me a flexible code writing.
Thanks in advance.
It's a standard practice in Objective-C to put the code to be executed after the authentication in the authenticationSucess: method. You might not like it, but that is life.
Many people had the same complaint as you, so
on iOS 4 and later, there's something called blocks which allow you to write the code to be executed after the authentication in the method which initiates the authentication, as in
[mService authenticateAndExecute:^{
code to be executed when successfully authenticated ;
} whenError:^{
code to be executed when authentication failed;
} ];
But in this case you need to modify the API, which is possible by using categories. See this blog post by Mike Ash. He has many other posts on blocks on the same blog, which are also very instructive.
If you're going to use a library that works asynchronously (and therefore doesn't block your UI), you should have a good reason for trying to force it to work synchronously.
You should be checking for an authentication error at the end of your authenticationSuccess:authenticatedWithError: method, and calling the next request from there if there's a success. Similarly, in your spreadsheetsTicket:finishedWithFeed:error: check for an error, and continuing processing if there isn't one. It might be a better design to do that continued work in a separate method, but that's up to you.
Is there a specific reason you want to use the GData API in a synchronous fashion?

How can my app detect a change to another app's window?

In Cocoa on the Mac, I'd like to detect when a window belonging to another app is moved, resized, or repainted. How can I do this?
You would need to use the Accessibility APIs, which are plain-C, located inside the ApplicationServices framework. For instance:
First you create an application object:
AXUIElementRef app = AXUIElementCreateApplication( targetApplicationProcessID );
Then you get the window from this. You can request the window list and enumerate, or you can get the frontmost window (look in AXAttributeConstants.h for all the attribute names you'd use).
AXUIElementRef frontWindow = NULL;
AXError err = AXUIElementCopyAttributeValue( app, kAXMainWindowAttribute, &frontWindow );
if ( err != kAXErrorSuccess )
// it failed -- maybe no main window (yet)
Now you can request notification via a C callback function when a property of this window changes. This is a four-step process:
First you need a callback function to receive the notifications:
void MyAXObserverCallback( AXObserverRef observer, AXUIElementRef element,
CFStringRef notificationName, void * contextData )
{
// handle the notification appropriately
// when using ObjC, your contextData might be an object, therefore you can do:
SomeObject * obj = (SomeObject *) contextData;
// now do something with obj
}
Next you need an AXObserverRef, which manages the callback routine. This requires the same process ID you used to create the 'app' element above:
AXObserverRef observer = NULL;
AXError err = AXObserverCreate( applicationProcessID, MyObserverCallback, &observer );
if ( err != kAXErrorSuccess )
// handle the error
Having got your observer, the next step is to request notification of certain things. See AXNotificationConstants.h for the full list, but for window changes you'll probably only need these two:
AXObserverAddNotification( observer, frontWindow, kAXMovedNotification, self );
AXObserverAddNotification( observer, frontWindow, kAXResizedNotification, self );
Note that the last parameter there is passing an assumed 'self' object as the contextData. This is not retained, so it's important to call AXObserverRemoveNotification when this object goes away.
Having got your observer and added notification requests, you now want to attach the observer to your runloop so you can be sent these notifications in an asynchronous manner (or indeed at all):
CFRunLoopAddSource( [[NSRunLoop currentRunLoop] getCFRunLoop],
AXObserverGetRunLoopSource(observer),
kCFRunLoopDefaultMode );
AXUIElementRefs are CoreFoundation-style objects, so you need to use CFRelease() to dispose of them cleanly. For cleanliness here, for example, you would use CFRelease(app) once you've obtained the frontWindow element, since you'll no longer need the app.
A note about Garbage-Collection: To keep an AXUIElementRef as a member variable, declare it like so:
__strong AXUIElementRef frontWindow;
This instructs the garbage collector to keep track of this reference to it. When assigning it, for compatibility with GC and non-GC, use this:
frontWindow = (AXUIElementRef) CFMakeCollectable( CFRetain(theElement) );
Further research turned up "Quartz Display Services"
The interesting function for my needs is CGRegisterScreenRefreshCallback.