I have an iOS program using Core Data backing onto DynamoDB using ARC.
In it I have a data model with the following class declared:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Track : NSManagedObject
@property (nonatomic, retain) NSString * trackId;
@end
-------------------------------------------------
#import "Track.h"
@implementation Track
@dynamic trackId;
@end
I then have a class creating an instance of the ManagedObject and persisting it like so:
NSString *trackId = @"ABC123";
Track *track = (Track*)[NSEntityDescription insertNewObjectForEntityForName:@"Track" inManagedObjectContext:context];
track.trackId=trackId;
NSError *error;
if (![appDelegate.managedObjectContext save:&error])
{
NSLog(@"error: %@", error);
}
This works as expected. However, if I implement the same using a switch to alter the value of trackId as below:
for (int i=0; i<1; i++) {
NSString *trackId;
switch (i) {
case 0:
trackId = @"XYZ789";
break;
}
Track *track = (Track*)[NSEntityDescription insertNewObjectForEntityForName:@"Track" inManagedObjectContext:context];
track.trackId=trackId;
}
NSError *error;
if (![appDelegate.managedObjectContext save:&error])
{
NSLog(@"error: %@", error);
}
then I get the following exception:
2013-01-16 14:44:00.013 DjTest2[2351:c07] XYZ789
2013-01-16 14:44:00.014 DjTest2[2351:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: key cannot be nil'
*** First throw call stack:
(0x183e012 0x1663e7e 0x18c10de 0x107c9bf 0x39799 0x1ff5e4 0xc7831 0xf533c 0x3411 0x68c817 0x68c882 0x5dba25 0x5dbdbf 0x5dbf55 0x5e4f67 0x5a8fcc 0x5a9fab 0x5bb315 0x5bc24b 0x5adcf8 0x268bdf9 0x268bad0 0x17b3bf5 0x17b3962 0x17e4bb6 0x17e3f44 0x17e3e1b 0x5a97da 0x5ab65c 0x258d 0x24b5)
libc++abi.dylib: terminate called throwing an exception
I assume there is some issue I'm not aware of regarding variable scope / retention using ARC where the NSString literal is created within the scope of a switch, but I can't find any reference to it.
Does anyone know what the root cause to this is and how you would efficiently deal with persisting a large number of objects without being able to perform such manipulation?
Note: I have mentioned backing on to DynamoDB for completeness, but this exception is raised before any attempt to call to AWS is made.