Realm Objective-C migration error - objective-c

I am seeing crashes via Crashlytics and hearing from customers that the application is crashing right as they open it.
This is narrowed down to the application migrating one of the realm databases. I have not been able to recreate the issue unfortunately because I am not able to make any sense of the error I am seeing.
I have logic that checks when the app starts up to check and see if the realm needs to be compacted. When doing that the realm determines that it needs to be migrated and hit the migration block.
config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
if (oldSchemaVersion < 17) {
[migration enumerateObjects:Event.className block:^(RLMObject *oldObject, RLMObject *newObject) {
NSString *className = [[oldObject[#"endDateTime"] objectSchema] className];
if ([className isEqualToString:#"DateObject"]) {
newObject[#"endDateTime"] = oldObject[#"endDateTime"][#"value"];
}
}];
}
};
Due to a mistake on my end when doing previous migrations I was manually checking to see if a property if of a specific type before deciding to migrate it.
Unfortunately when doing so the oldObject which should be of type RLMObject seems to be of type NSTaggedDate according to Crashlytics
[__NSTaggedDate objectSchema]: unrecognized selector sent to instance 0xe41bf592ee000000
Fatal Exception: NSInvalidArgumentException
0 CoreFoundation 0x186419d04 __exceptionPreprocess
1 libobjc.A.dylib 0x185668528 objc_exception_throw
2 CoreFoundation 0x1864271c8 __methodDescriptionForSelector
3 CoreFoundation 0x18641f6b0 ___forwarding___
4 CoreFoundation 0x18630501c _CF_forwarding_prep_0
5 MY_mobile_ios_common 0x10199c8c0 __34+[MYRealm getRealmConfigByName:]_block_invoke_2 (MYRealm.m:44)
6 Realm 0x1011b6598 -[RLMMigration enumerateObjects:block:] (RLMMigration.mm:99)
7 MY_mobile_ios_common 0x10199c830 __34+[MYRealm getRealmConfigByName:]_block_invoke (MYRealm.m:40)
8 Realm 0x1011b6ab4 -[RLMMigration execute:] (RLMMigration.mm:131)
9 Realm 0x1012297ec std::__1::__function::__func<+[RLMRealm realmWithConfiguration:error:]::$_1, std::__1::allocator<+[RLMRealm realmWithConfiguration:error:]::$_1>, void (std::__1::shared_ptr<realm::Realm>, std::__1::shared_ptr<realm::Realm>, realm::Schema&)>::operator()(std::__1::shared_ptr<realm::Realm>&&, std::__1::shared_ptr<realm::Realm>&&, realm::Schema&) (RLMRealm.mm:410)
10 Realm 0x10124fa90 std::__1::__function::__func<realm::Realm::update_schema(realm::Schema, unsigned long long, std::__1::function<void (std::__1::shared_ptr<realm::Realm>, std::__1::shared_ptr<realm::Realm>, realm::Schema&)>, std::__1::function<void (std::__1::shared_ptr<realm::Realm>)>, bool)::$_2, std::__1::allocator<realm::Realm::update_schema(realm::Schema, unsigned long long, std::__1::function<void (std::__1::shared_ptr<realm::Realm>, std::__1::shared_ptr<realm::Realm>, realm::Schema&)>, std::__1::function<void (std::__1::shared_ptr<realm::Realm>)>, bool)::$_2>, void ()>::operator()() (memory:4625)
11 Realm 0x101181f64 realm::ObjectStore::apply_schema_changes(realm::Group&, unsigned long long, realm::Schema&, unsigned long long, realm::SchemaMode, std::__1::vector<realm::SchemaChange, std::__1::allocator<realm::SchemaChange> > const&, std::__1::function<void ()>) (object_store.cpp:753)
12 Realm 0x10124bbb8 realm::Realm::update_schema(realm::Schema, unsigned long long, std::__1::function<void (std::__1::shared_ptr<realm::Realm>, std::__1::shared_ptr<realm::Realm>, realm::Schema&)>, std::__1::function<void (std::__1::shared_ptr<realm::Realm>)>, bool) (functional:1860)
13 Realm 0x101226a10 +[RLMRealm realmWithConfiguration:error:] (functional:1860)
14 MY_mobile_ios_common 0x10199cba0 +[MYRealm mainRealmCompact] (MYRealm.m:137)
15 MY App 0x1002b49dc -[AppDelegate compactRealmIfNeeded] (AppDelegate.m:808)
16 MY App 0x1002af940 -[AppDelegate application:didFinishLaunchingWithOptions:] (AppDelegate.m:48)
Any thoughts on what I could be doing wrong here, am about to just delete the realm databases and force the users to go back through the initial loading of data again.
ProductName: Mac OS X
ProductVersion: 10.12.6
BuildVersion: 16G1036
/Applications/Xcode.app/Contents/Developer
Xcode 9.1
Build version 9B55
/usr/local/bin/pod
1.3.1
Realm (2.10.2)
Realm (= 2.10.2)
/bin/bash
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16)
(not in use here)
/usr/local/bin/git
git version 2.12.2

The crash log is telling you that your call to [oldObject[#"endDateTime"] objectSchema] is seeing oldObject[#"endDateTime"] evaluate to an NSDate, which does not respond to -objectSchema. If the endDateTime property can be of different types depending on which schema version you're updating from, you'll need to do further checks on the object before sending -objectSchema to it.

Related

Why doesn't #try...#catch work with -[NSFileHandle writeData]?

I have a method that is similar to the tee utility. It receives a notification that data has been read on a pipe, and then writes that data to one or more pipes (connected to subordinate applications). If a subordinate app crashes, then that pipe is broken, and I naturally get an exception, which is then handled in a #try...#catch block.
This works most of the time. What I'm puzzled by is that occasionally, the exception crashes the app entirely with an uncaught exception, and pointing to the writeData line . I haven't been able to figure out what the pattern is on when it crashes, but why should it ever NOT be caught? (Note this is not executing inside the debugger.)
Here's the code:
//in setup:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tee:) name:NSFileHandleReadCompletionNotification object:fileHandle];
-(void)tee:(NSNotification *)notification
{
// NSLog(#"Got read for tee ");
NSData *readData = notification.userInfo[NSFileHandleNotificationDataItem];
totalDataRead += readData.length;
// NSLog(#"Total Data Read %ld",totalDataRead);
NSArray *pipes = [teeBranches objectForKey:notification.object];
if (readData.length) {
for (NSPipe *pipe in pipes {
#try {
[[pipe fileHandleForWriting] writeData:readData];
}
#catch (NSException *exception) {
NSLog(#"download write fileHandleForWriting fail: %#", exception.reason);
if (!_download.isCanceled) {
[_download rescheduleOnMain];
NSLog(#"Rescheduling");
}
return;
}
#finally {
}
}
}
I should mention that I have set a signal handler in my AppDelegate>appDidFinishLaunching:
signal(SIGPIPE, &signalHandler);
signal(SIGABRT, &signalHandler );
void signalHandler(int signal)
{
NSLog(#"Got signal %d",signal);
}
And that does execute whether the app crashes or the signal is caught.
Here's a sample crash backtrace:
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Application Specific Information:
*** Terminating app due to uncaught exception 'NSFileHandleOperationException', reason: '*** -[NSConcreteFileHandle writeData:]: Broken pipe'
abort() called
terminating with uncaught exception of type NSException
Application Specific Backtrace 1:
0 CoreFoundation 0x00007fff838cbbec __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff90e046de objc_exception_throw + 43
2 CoreFoundation 0x00007fff838cba9d +[NSException raise:format:] + 205
3 Foundation 0x00007fff90a2be3c __34-[NSConcreteFileHandle writeData:]_block_invoke + 81
4 Foundation 0x00007fff90c53c17 __49-[_NSDispatchData enumerateByteRangesUsingBlock:]_block_invoke + 32
5 libdispatch.dylib 0x00007fff90fdfb76 _dispatch_client_callout3 + 9
6 libdispatch.dylib 0x00007fff90fdfafa _dispatch_data_apply + 110
7 libdispatch.dylib 0x00007fff90fe9e73 dispatch_data_apply + 31
8 Foundation 0x00007fff90c53bf0 -[_NSDispatchData enumerateByteRangesUsingBlock:] + 83
9 Foundation 0x00007fff90a2bde0 -[NSConcreteFileHandle writeData:] + 150
10 myApp 0x000000010926473e -[MTTaskChain tee:] + 2030
11 CoreFoundation 0x00007fff838880dc __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
12 CoreFoundation 0x00007fff83779634 _CFXNotificationPost + 3140
13 Foundation 0x00007fff909bb9b1 -[NSNotificationCenter postNotificationName:object:userInfo:] + 66
14 Foundation 0x00007fff90aaf8e6 _performFileHandleSource + 1622
15 CoreFoundation 0x00007fff837e9ae1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
16 CoreFoundation 0x00007fff837dbd3c __CFRunLoopDoSources0 + 476
17 CoreFoundation 0x00007fff837db29f __CFRunLoopRun + 927
18 CoreFoundation 0x00007fff837dacb8 CFRunLoopRunSpecific + 296
19 HIToolbox 0x00007fff90664dbf RunCurrentEventLoopInMode + 235
20 HIToolbox 0x00007fff90664b3a ReceiveNextEventCommon + 431
21 HIToolbox 0x00007fff9066497b _BlockUntilNextEventMatchingListInModeWithFilter + 71
22 AppKit 0x00007fff8acf5cf5 _DPSNextEvent + 1000
23 AppKit 0x00007fff8acf5480 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 194
24 AppKit 0x00007fff8ace9433 -[NSApplication run] + 594
25 AppKit 0x00007fff8acd4834 NSApplicationMain + 1832
26 myApp 0x00000001091b16a2 main + 34
27 myApp 0x00000001091ab864 start + 52
So, the nice folks at Crashlytics were able to help me here. To quote them:
Here's the story:
The pipe dies because the child process crashes. The very next read/write will cause a fault.
That write occurs, which results in a SIGPIPE (not a runtime exception).
If that SIGPIPE is masked/ignored, NSFileHandle checks errno and creates a runtime exception which it throws.
A function deeper than your tee: method has wrapped this write in a #try/#catch (proved by setting a breakpoint on __cxa_begin_catch)
That function, which turns out to be "_dispatch_client_callout", which makes a call to objc_terminate, which effectively kills the
process.
Why does _dispatch_client_callout do this? I'm not sure, but you can
see the code here:
http://www.opensource.apple.com/source/libdispatch/libdispatch-228.23/src/object.m
Unfortunately, AppKit has a really poor track record of being a good
citizen in the face of runtime exceptions.
So, you are right that NSFileHandle raises a runtime exception about
the pipe dying, but not before a signal is raised that kills the
process. Others have encountered this exact issue (on iOS, which has
much better semantics about runtime exceptions).
How can I catch EPIPE in my NSFIleHandle handling?
In short, I don't believe it is possible for you to catch this
exception. But, by ignoring SIGPIPE and using lower-level APIs to
read/write to this file handle, I believe you can work around this. As
a general rule, I'd recommend against ignoring signals, but in this
case, it seems reasonable.
Thus the revised code is now:
-(void)tee:(NSNotification *)notification {
NSData *readData = notification.userInfo[NSFileHandleNotificationDataItem];
totalDataRead += readData.length;
// NSLog(#"Total Data Read %ld",totalDataRead);
NSArray *pipes = [teeBranches objectForKey:notification.object];
if (readData.length) {
for (NSPipe *pipe in pipes ) {
NSInteger numTries = 3;
size_t bytesLeft = readData.length;
while (bytesLeft > 0 && numTries > 0 ) {
ssize_t amountSent= write ([[pipe fileHandleForWriting] fileDescriptor], [readData bytes]+readData.length-bytesLeft, bytesLeft);
if (amountSent < 0) {
NSLog(#"write fail; tried %lu bytes; error: %zd", bytesLeft, amountSent);
break;
} else {
bytesLeft = bytesLeft- amountSent;
if (bytesLeft > 0) {
NSLog(#"pipe full, retrying; tried %lu bytes; wrote %zd", (unsigned long)[readData length], amountSent);
sleep(1); //probably too long, but this is quite rare
numTries--;
}
}
}
if (bytesLeft >0) {
if (numTries == 0) {
NSLog(#"Write Fail4: couldn't write to pipe after three tries; giving up");
}
[self rescheduleOnMain];
}
}
}
}
I know this doesn't do much to answer why the exception catching seems broken, but I hope that this is a helpful answer to workaround the issue.
I faced a similar issue trying to read/write to a socket wrapped in an NSFileHandle. I worked around it by testing the pipe availability directly with the fileDescriptor like so
- (BOOL)socketIsValid
{
return (write([fh fileDescriptor], NULL, 0) == 0);
}
then I tested with that method before attempting to call writeData:.

NSInvalidUnarchiveOperationException when unarchieving custom class

edit:
By adding QCAnnonce* a = [[QCAnnonce alloc] init];In my code somewhere before the function call, I solved the problem, so I guess that I "introduced the class to the runtime". But I have now a warning saying that "a" is unused, so is there a runtime function I can use to "introduce the class to the runtime"?
I am trying to create a client-server application. The objects are archived and unarchived for transmission using NSKeyed(Un)Archiver. Most of my objects are transmitted without any problem, but one of them raise an NSInvalidUnarchiveOperationException.
The exception is called before the breakpoint I placed in initWithCoder:.
I have tried to archive/unarchive before sending and this works well, so it shouldn't be an issue with initWithCoder.
I have tried to create a client in my server app (not in a separate app as my client) and he can decode the object. I can't see any difference between my client and this new client except that they are not in the same app.
The best guess I have is this part of the apple doc:
The delegate may, for example, load some code to introduce the class
to the runtime and return the class, or substitute a different class
object. If the delegate returns nil, unarchiving aborts and the method
raises an NSInvalidUnarchiveOperationException.
But I have no idea what "introduce the class to the runtime" means.
Here are this object methods for encoding/decoding:
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
a_listeAnnonces = [aDecoder decodeObjectForKey:#"Cartes"];
a_points = [aDecoder decodeIntForKey:#"Points"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:a_listeAnnonces forKey:#"Cartes"];
[aCoder encodeInt:a_points forKey:#"Points"];
}
Here is the exception message:
2014-06-04 11:27:34.681 myApp[3693:303] *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (QCAnnonce)
2014-06-04 11:27:34.794 myApp[3693:303] (
0 CoreFoundation 0x00007fff8937a25c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff8e898e75 objc_exception_throw + 43
2 CoreFoundation 0x00007fff8937a10c +[NSException raise:format:] + 204
3 Foundation 0x00007fff8a8acdd9 _decodeObjectBinary + 2349
4 Foundation 0x00007fff8a8ac34d _decodeObject + 288
5 Foundation 0x00007fff8a8d15a5 +[NSKeyedUnarchiver unarchiveObjectWithData:] + 92
6 myApp 0x000000010001365f -[QNProtocolWrap performMethod:withArgumentDatas:onObject:] + 543
7 myApp 0x000000010001261b -[QNConnection methodCall:withArguments:] + 251
8 myApp 0x0000000100012b23 -[QNConnection connectionBaseDidRecieveNewData:] + 211
9 myApp 0x0000000100012b8b -[QNConnection connectionBaseDidRecieveNewData:] + 315
10 myApp 0x000000010000e38c -[QNConnectionBase readInput] + 204
11 myApp 0x000000010000e591 -[QNConnectionBase stream:handleEvent:] + 449
12 CoreFoundation 0x00007fff892ebc81 _signalEventSync + 385
13 CoreFoundation 0x00007fff892ebac8 _cfstream_solo_signalEventSync + 328
14 CoreFoundation 0x00007fff892eb93f _CFStreamSignalEvent + 623
15 CFNetwork 0x00007fff81e4401a _ZN29CoreReadStreamCFStreamSupport19coreStreamReadEventEP16__CoreReadStreamm + 102
16 CFNetwork 0x00007fff81e43f89 _ZN20CoreReadStreamClient25coreStreamEventsAvailableEm + 53
17 CFNetwork 0x00007fff81f77a65 _ZN14CoreStreamBase14_callClientNowEP16CoreStreamClient + 53
18 CFNetwork 0x00007fff81e43ca9 _ZN14CoreStreamBase34_streamSetEventAndScheduleDeliveryEmh + 183
19 CFNetwork 0x00007fff81e43a32 _ZN12SocketStream40dispatchSignalFromSocketCallbackUnlockedEP24SocketStreamSignalHolder + 74
20 CFNetwork 0x00007fff81e43160 _ZN12SocketStream14socketCallbackEP10__CFSocketmPK8__CFDataPKv + 206
21 CFNetwork 0x00007fff81e43062 _ZN12SocketStream22_SocketCallBack_streamEP10__CFSocketmPK8__CFDataPKvPv + 64
22 CoreFoundation 0x00007fff892eb107 __CFSocketPerformV0 + 855
23 CoreFoundation 0x00007fff892ab661 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
24 CoreFoundation 0x00007fff8929cd12 __CFRunLoopDoSources0 + 242
25 CoreFoundation 0x00007fff8929c49f __CFRunLoopRun + 831
26 CoreFoundation 0x00007fff8929bf25 CFRunLoopRunSpecific + 309
27 HIToolbox 0x00007fff89726a0d RunCurrentEventLoopInMode + 226
28 HIToolbox 0x00007fff897267b7 ReceiveNextEventCommon + 479
29 HIToolbox 0x00007fff897265bc _BlockUntilNextEventMatchingListInModeWithFilter + 65
30 AppKit 0x00007fff82a9526e _DPSNextEvent + 1434
31 AppKit 0x00007fff82a948bb -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 122
32 AppKit 0x00007fff82a889bc -[NSApplication run] + 553
33 AppKit 0x00007fff82a737a3 NSApplicationMain + 940
34 myApp 0x0000000100001262 main + 34
35 myApp 0x0000000100001234 start + 52
36 ??? 0x0000000000000003 0x0 + 3
)
It seems that Class is not loaded to runtime at the moment when you are trying to decode it by NSKeyedArchiver.
If it's not loaded, NSKeyedArchiver just can't find class QCAnnounce. (And that's why it can't decode it)
To check this, you may look in the + (void)load method of NSObject protocol.
The runtime sends this message once per a class right after the Class is loaded into process's address space.
For classes that are part of the program's executable file, the runtime sends the load message very early in the process's lifetime. For classes that are in a shared (dynamically-loaded) library, the runtime sends the load message just after the shared library is loaded into the process's address space.
You can check this by overloading +(void)load method and setting breakpoint there and see if it's have been loaded to runtime before you are calling unarchive.
+ (void)load {
NSLog(#"%# loaded!", self);
}
Your fix [[QCAnnounce alloc] init] works because when Runtime is trying to send first message to a class, it needs to call +(void)initialize to that class and by the time you receive initialize, class in your process should have already received load.
The problem here is that the runtime didn't load all the class present in my static library. As I had no direct call to that class (only id), it was never loaded.
I fixed it by adding -objC in "other linker flags" in the build settings.
Some informations about why this was a good idea were found in this Technical Q&A:
-objC causes the linker to load every object file in the library that defines an Objective-C class or category
There exists two others flags (same Q&A):
-all_load forces the linker to load all object files from every archive it sees, even those without Objective-C code. -force_load is available in Xcode 3.2 and later. It allows finer grain control of archive loading. Each -force_load option must be followed by a path to an archive, and every object file in that archive will be loaded.

Stack overflow in release binary but not in Xcode-Debugger

My (Cocoa)-App runs perfectly fine when I start it from within Xcode. However when I archive / release it, that version will crash. The error reporter that pops open says:
[...]
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Application Specific Information:
[9082] stack overflow
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 libsystem_kernel.dylib 0x00007fff944a7212 __pthread_kill + 10
1 libsystem_c.dylib 0x00007fff9290caf4 pthread_kill + 90
2 libsystem_c.dylib 0x00007fff92950e9e __abort + 159
3 libsystem_c.dylib 0x00007fff92951d17 __stack_chk_fail + 195
[...]
While it also gives me the line of code where execution stopped, this really does not help me as the exact same code path is executed in debug mode (but succeedes).
So I'm wondering: might it actually be that the stack sizes are different for a release and a debug version? And how big is the stack after all on a Mac (64 bit / Mountain Lion)? I'm not aware of putting insanely much data on the stack...
If I have too much data on the stack, what patterns would I need to avoid to reduce my stack load?
[Update]
ok, I got my App running by adding the -fno-stack-protector flag. (BTW: I'm compiling with LLVM)
Before that, I stepped through the crashing code line by line and found the following bahaviour which I don't understand:
the method foo(x) calls bacon(x). x is 8 and is handed from foo to bacon without modification. Yet when I step into bacon(x), x suddenly is 4295939448 (each time). If I set -fno-stack-protector the value is correct.
To my naive eyes, this looks as if the stack-protector sets the magic value 4295939448 somewhere in the stack and makes it read-only. And while my functions put their parameters on the stack, at some point parameter x happens to be put on that magic address and thus cannot be written (subsequent parameters seem to be written correctly). In my case x is a buffer length parameter, which naturally leads to a buffer-overflow and crash.
Does somebody have a deeper understanding of the stack-protector? Why is this happening? And in what cases is it safe and legal to disable the stack-protector and in what cases is it dangerous?
[Update 2: Original Code]
This method calls the other Decrypt below. stIVLen at that point is 8
BOOL CEracomSE::Decrypt(
PBYTE pMsg, size_t stLen,
const CSK* pKey /* = NULL */,
PBYTE pIV /* = NULL */, size_t stIVLen /* = 0 */,
FBM fbm /* = FBM_CBC */,
PADDING padding /* = NO_PADDING */
)
{
//stIVLen == 8
return Decrypt( (uint64_t)0, pMsg, stLen, pKey, pIV, stIVLen, fbm, padding );
}
When Decrypt is called stIVLen is 4295939448, the other parameter are still correct
BOOL CEracomSE::Decrypt(
uint64_t qwOffset,
PBYTE pMsg, size_t stLen,
const CSK* pKey /* = NULL */,
PBYTE pIV /* = NULL */, size_t stIVLen /* = 0 */,
FBM fbm /* = FBM_CBC */,
PADDING padding /* = NO_PADDING */
)
{
//stIVLen now is 4295939448
BYTE a_iv[16] = {0};
size_t a_iv_len;
BYTE a_key[32] = {0};
size_t a_key_len = 0;
size_t nBytes;
size_t nDataOffset;
size_t nRemainingData = stLen;
bool ret;
//[...]
}
I recently faced this situation with my app. I know its an old thread but responding anyways with the intent that someone else could benefit from the findings.
Passing -fno-stack-protector did solve the problem as suggested in the question. However, digging a little deeper we found that, changing all occurrences of literal array declaration to a longer declaration did solve the problem without passing the compiler flag.
so changing all occurrences of
#[#(1), #(2)]
to
[NSArray arrayWithObjects:#(1), #(2), nil]
May be its specific to our app only but hope it helps others as well.

Crash with RestKit when issuing multiple requests in quick succession

I have a button with two buttons which start the download of some data from a web server with RestKit.
Now if the user taps the two buttons repeatedly in quick succession my app crashes and produces the crash log below.
I initiate my requests like so:
-(void)loadDataAtPath:(NSString *)path completion:(ResultArrayBlock)completionBlock failed:(ResultFailedBlock)failedBlock
{
RKObjectMapping *groupMapping = [Group mapping];
[self.objectManager.mappingProvider setMapping:groupMapping forKeyPath:#"groups.group"];
[self.objectManager.mappingProvider setObjectMapping:groupMapping forKeyPath:path];
[self.objectManager loadObjectsAtResourcePath:path usingBlock:^(RKObjectLoader *loader) {
loader.onDidLoadObjects = ^(NSArray *array){
// Do the reverse mapping of the group
for (Group *c in array) {
for(Person *p in c.persons){
p.group = c;
}
}
completionBlock(array);
};
loader.onDidFailWithError = failedBlock;
}];
}
I first thought that the problem was the for-loop where I do some after-mapping setup of my data, but the problem still persists even when commenting the for-loop.
Curiously this problem does not occur in the simulator even when I switch on the Network Link Conditioner.prefpane
The crash
When I debug this on the device I get the following on the console.
[PLCrashReport] Terminated stack walking early: Corrupted frame
[PLCrashReport] Terminated stack walking early: Corrupted frame
The crash log looks like this:
Application Specific Information:
*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSCFDictionary: 0x3c14a0> was mutated while being enumerated.'
Last Exception Backtrace:
0 CoreFoundation 0x3734e88f __exceptionPreprocess + 162
1 libobjc.A.dylib 0x35053259 objc_exception_throw + 32
2 CoreFoundation 0x3734e3b3 __NSFastEnumerationMutationHandler + 162
3 MyApp 0x0008f5bf -[RKObjectMapper performKeyPathMappingUsingMappingDictionary:] + 407
4 MyApp 0x0008fa45 -[RKObjectMapper performMapping] + 673
5 MyApp 0x0008ac7d -[RKObjectLoader mapResponseWithMappingProvider:toObject:inContext:error:] + 1045
6 MyApp 0x0008b04f -[RKObjectLoader performMapping:] + 575
7 MyApp 0x0008b22b __47-[RKObjectLoader performMappingInDispatchQueue]_block_invoke_0 + 247
8 libdispatch.dylib 0x3046ec59 _dispatch_call_block_and_release + 12
9 libdispatch.dylib 0x30479cab _dispatch_queue_drain + 274
10 libdispatch.dylib 0x30479b19 _dispatch_queue_invoke$VARIANT$up + 36
11 libdispatch.dylib 0x3047a78b _dispatch_worker_thread2 + 214
12 libsystem_c.dylib 0x33bbddfb _pthread_wqthread + 294
13 libsystem_c.dylib 0x33bbdcd0 start_wqthread + 8
As #PhillipMills suggested, you can easily see the answer when you look inside performKeyPathMappingUsingMappingDictionary. Your problem is repeatedly setting the mapping with these lines:
[self.objectManager.mappingProvider setMapping:groupMapping forKeyPath:#"groups.group"];
[self.objectManager.mappingProvider setObjectMapping:groupMapping forKeyPath:path];
If you call this line while the response is being mapping it triggers the error because you are changing the same dictionary it is trying to fast enumerate over.
Normally, you would set the mapping somewhere in the initial configuration and NOT each time like this.

Boost serialization: archive "unsupported version" exception

I've got the exception "unsupported version" when I try to deserialize through a text archive some data previously serialized with a upper version of Boost (1.46 to serialize and 1.38 to deserialize)...is there a way to downgrade (in the code) the serialization?
Something like "set_library_version"?
See the Error read binary archive, created by old Boost version mail archive post about the serialization error.
It says that the code below does the job:
void load_override(version_type & t, int version){
library_version_type lvt = this->get_library_version();
if (boost::archive::library_version_type(7) < lvt){
this->detail_common_iarchive::load_override(t, version);
}
else
if (boost::archive::library_version_type(6) < lvt){
uint_least16_t x = 0;
* this->This() >> x;
t = boost::archive::version_type(x);
}
else
if (boost::archive::library_version_type(3) == lvt ||
boost::archive::library_version_type(5) == lvt){
#pragma message("CTMS fix for serialization bug (lack of backwards compatibility) introduced by Boost 1.45.")
// Up to 255 versions
unsigned char x = 0;
* this->This() >> x;
t = version_type(x);
}
else{
unsigned int x = 0;
* this->This() >> x;
t = boost::archive::version_type(x);
}
}
Using text_archive ... I had a recent issue with this also.
I recently upgraded boost from 1.67 to 1.72 on Windows, generated some data on Windows. When I ran the data on my Linux environment which is still on Boost 1.67, it throws not supported.
The header for 1.67 looked like this
22 serialization::archive 16
and 1.72 looked like
22 serialization::archive 17
I changed 17 to 16 and it was happy for my use case.