I use Quickblox for my chatting app and use core data to store message history.
When I log in to the chat, I resend messages that was failed to send last time. (i.e. I fetch messages from Core Data and get the unsent ones)
Some times it works, but some times the app crashes on the helper method (which is used to get the Core Data context):
+ (NSManagedObjectContext *)context {
return ((AppDelegate *)[UIApplication sharedApplication].delegate).managedObjectContext;
}
I didn't change anything for App Delegate, it's just a normal CoreData enabled AppDelegate:
@interface AppDelegate : UIResponder <UIApplicationDelegate, QBActionStatusDelegate, QBChatDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
@end
This is how I retrieve a message history in a DBHelper class
+ (NSMutableArray *)fetchMessagesWithSenderID:(NSString *)userID {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Message" inManagedObjectContext:[DBHelper context]]; //the app crashes here, inside [DBHelper context]
[fetchRequest setEntity:entity];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"sender.userID = %@", userID];
[fetchRequest setPredicate:pred];
NSError *error;
NSMutableArray *fetchedObjects = [[DBHelper context] executeFetchRequest:fetchRequest error:&error].mutableCopy;
return fetchedObjects;
}
Log:
2014-01-05 16:32:05.365 Chat[1517:60b] completedWithResult: <QBMRegisterSubscriptionTaskResult: 0x14e955e0>
2014-01-05 16:32:05.366 Chat[1517:60b] error: (
"Invalid provisioning profiles. You have to use valid Provisioning Profiles for your project"
)
2014-01-05 16:32:06.549 Chat[1517:180f] QBChat/didConnect
2014-01-05 16:32:07.913 Chat[1517:4103] -[QBChat xmppStreamDidAuthenticate:] -> user: 573782, supportsStartTLS: 1, isSecure: 0
2014-01-05 16:32:07.913 Chat[1517:60b] chatDidLogin
2014-01-05 16:32:07.916 Chat[1517:60b] -[QBMGetTokenPerformer managedObjectContext]: unrecognized selector sent to instance 0x14d48800
(lldb)
Try to move all CoreData logic from AppDelegate to separate singleton:
*.h file:
@interface CoreDataService : NSObject
+(instancetype)instance;
- (void)saveContext;
@end
*.m file:
@implementation CoreDataService
@property (readonly, strong, nonatomic) NSManagedObjectContext
*managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator
*persistentStoreCoordinator;
- (void)saveContext{
...
}