Coredata unable to delete the existing record + multithreading - objective-c

I am parsing xml , inserting an entity in the database, for updating record I am again adding that record and deleting the older record. But it is not able to delete the older entry so I am able to see duplicate entries.
- (void)insertSampleWithId:(NSString *)sampleId{
__block NSError *lError = nil;
dispatch_queue_t categoryCustomQueue = dispatch_queue_create("com.xyz.sample”, NULL);
dispatch_sync(categoryCustomQueue, ^{
NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
[dnc addObserver:self
selector:#selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:_tempMOC];
_supplier = [NSEntityDescription insertNewObjectForEntityForName:#"BSSample” inManagedObjectContext:_tempMOC];
_supplier.sampleId = supplierId;
// double delayInSeconds = 0.3;
// dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//
// dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//
// });
[self ifSupplierPresentInMainContextRemoveIt:supplierId];
if(![_tempMOC save:&lError]){
NSLog(#"Error adding while category %# ,%# ,%#", lError, [lError userInfo], [lError localizedDescription]);
}
[dnc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:_tempMOC];
});
}
- (BOOL)ifSamplePresentInMainContextRemoveIt:(NSString *)sampleId{
__block BSSampler *suppl = nil;
NSManagedObjectContext *managedObjectContext = dataManager.coreDataHelper.context;
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:#"BSSample” inManagedObjectContext:managedObjectContext];
[_fetchRequest setEntity:entityDescription];
[_fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"sampleId == '%#'", supplierId]];
[_fetchRequest setResultType:NSDictionaryResultType];
[_fetchRequest setReturnsDistinctResults:YES];
NSError *error;
NSArray *array = [managedObjectContext executeFetchRequest:_fetchRequest error:&error];
if(array != nil && [array count]>0){
suppl = [array objectAtIndex:0];
}
if(suppl)
[dataManager.coreDataHelper.context deleteObject:suppl];
return [dataManager.coreDataHelper.context save:&error];
}
- (void)mergeChanges:(NSNotification *)saveNotification{
[self performSelectorOnMainThread:#selector(mergeToMainThred:) withObject:saveNotification waitUntilDone:NO];
}
- (void)mergeToMainThred:(NSNotification*)saveNotification{
[dataManager.coreDataHelper.context mergeChangesFromContextDidSaveNotification:saveNotification];
}

There is no code here that shows your delete.
You say that are not able to delete but you don't say why or how. What is failing? What is your expectation and what is the actual results?
What does mergeChanges: look like?
Please update your question so that we have a chance of understanding the issue.

Related

NSRangeException while deleting UICollectionView cells

I'm trying to remove cells from UICollectionView in for.. in loop and every time I get NSRangeException. I can't understand why does it happen because firstly I sort my array and then trying to remove. So the problem is that I firstly try to send request to the server and only if response is succes my UICollectionView cells and array elements are removes. Here is my code:
Pass elements through the loop:
- (IBAction)deletePictures:(id)sender {
int i = 0;
if (selectedPhotosURL.count>0){
loadCount = (int)selectedPhotosURL.count;
//sorting an array (it works fine)
NSArray *indexPaths = sortMediaCollection.indexPathsForSelectedItems;
NSMutableArray *pathes = [NSMutableArray arrayWithArray:indexPaths];
NSSortDescriptor *highestToLowest = [NSSortDescriptor sortDescriptorWithKey:#"self" ascending:NO];
[pathes sortUsingDescriptors:[NSArray arrayWithObject:highestToLowest]];
[selecedCellsArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
return [str2 compare:str1 options:(NSNumericSearch)];
}];
NSLog(#"selectedCElls %#",selecedCellsArray);
for(NSIndexPath *indexPath in pathes) {
NSLog(#"indexPath in pathes is %ld",(long)indexPath.row);
AVMSMCell *cell = (AVMSMCell *)[sortMediaCollection cellForItemAtIndexPath:indexPath];
AVMDataStore *oneItem = [smArray objectAtIndex:indexPath.row];
NSString *contentId = oneItem.fileId;
if (i<selectedPhotosURL.count){
NSLog(#"indexPath second loop is %ld",(long)indexPath.row);
[self deleteUserPhotos:contentId : indexPath.row : cell]; // send request to the server it's ok too.
i++;
}
}
} else {
[self selectAtLeastOneFirst];
}
}
For example here I select 6 cells and my array sort with right order from up to down (5,4,3,2,1,0). Then I pass this elements in method with this order.
Request send method:
-(void)deleteUserPhotos : (NSString *)contentId : (NSInteger )pathRow : (AVMSMCell *) cell{
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)pathRow];
if (([selecedCellsArray containsObject:[NSString stringWithFormat:#"%#",rowNsNum]]) )
{
cell.selectedBG.backgroundColor = DANGER;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *token = [defaults objectForKey:#"token"];
NSString *header = [NSString stringWithFormat:#"Bearer %#",token];
NSDictionary *params = #{#"lang": #"en",#"content_id":contentId,#"project_id":[defaults objectForKey:#"project_id"]};
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:header forHTTPHeaderField:#"Authorization"];
[manager POST:#"http://example.com/api/project/delete-content" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"JSON: %#", responseObject);
if ([[responseObject objectForKey:#"result"] isEqualToString:#"success"]){
#try{
NSLog(#"pathRow in TRY %ld",(long)pathRow); // HERE I get wrong number after two or three elements already passed
[smArray removeObjectAtIndex:(unsigned int)pathRow];
[selecedCellsArray removeObject:[NSString stringWithFormat:#"%ld",(long)pathRow]];
cell.selectedBG.hidden = YES;
[sortMediaCollection reloadSections:[NSIndexSet indexSetWithIndex:0]];
loadCount--;
}
} #catch (NSException *e){
NSLog(#"something is bad %#",e);
[SVProgressHUD dismiss];
if (smArray.count<pathRow-1){
[smArray removeObjectAtIndex:(unsigned int)pathRow-1];
}
} #finally {
cell.selectedBG.hidden = YES;
[sortMediaCollection reloadSections:[NSIndexSet indexSetWithIndex:0]];
}
} else {
NSLog(#"can't delete photo!");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"Error: %#", error);
errorEndSpinner
}];
}
}
So in method above I get wrong element number after two or three elements already passed i.e frist element is 5,then 4, then 2, 3,1,0.
And at this moment my #catch handle exception and trying to remove element with [smArray removeObjectAtIndex:(unsigned int)pathRow-1]; and then I get NSRangeException and my app crashing. What I do wrong?
I solved my problem with this answer and little bit modified my code.
I've got an NSRangeException because I removed my UICollectionView items through the loop. Instead I should better use multiple deleting instantly like this:
// Delete the items from the data source.
[self deleteItemsFromDataSourceAtIndexPaths:selectedItemsIndexPaths];
// Now delete the items from the collection view.
[sortMediaCollection deleteItemsAtIndexPaths:selectedItemsIndexPaths];
So now my code looks like:
Pass through the loop:
- (IBAction)deletePictures:(id)sender {
int i = 0;
if (selectedPhotosURL.count>0){
[SVProgressHUD showWithStatus:#"Deleting" maskType:SVProgressHUDMaskTypeBlack];
loadCount = (int)selectedPhotosURL.count;
NSArray *indexPaths = sortMediaCollection.indexPathsForSelectedItems;
NSMutableArray *pathes = [NSMutableArray arrayWithArray:indexPaths];
NSSortDescriptor *highestToLowest = [NSSortDescriptor sortDescriptorWithKey:#"self" ascending:NO];
[pathes sortUsingDescriptors:[NSArray arrayWithObject:highestToLowest]];
[selecedCellsArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
return [str2 compare:str1 options:(NSNumericSearch)];
}];
for(NSIndexPath *indexPath in pathes) {
AVMSMCell *cell = (AVMSMCell *)[sortMediaCollection cellForItemAtIndexPath:indexPath];
AVMDataStore *oneItem = [smArray objectAtIndex:indexPath.row];
NSString *contentId = oneItem.fileId;
if (i<selectedPhotosURL.count){
[self deleteUserPhotos:contentId : indexPath.row : cell pathes:pathes]; //pass array with pathes into 'deleteUserPhotos'
i++;
}
}
} else {
[self selectAtLeastOneFirst];
}
}
Main method:
-(void)deleteItemsFromDataSourceAtIndexPaths:(NSArray *)itemPaths {
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSIndexPath *itemPath in itemPaths) {
[indexSet addIndex:itemPath.row];
}
[smArray removeObjectsAtIndexes:indexSet];
}
-(void)deleteUserPhotos : (NSString *)contentId : (NSInteger )pathRow : (AVMSMCell *) cell pathes:(NSMutableArray*)selectedItemsIndexPaths{
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)pathRow];
if (([selecedCellsArray containsObject:[NSString stringWithFormat:#"%#",rowNsNum]]))
{
cell.selectedBG.backgroundColor = DANGER;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *token = [defaults objectForKey:#"token"];
NSString *header = [NSString stringWithFormat:#"Bearer %#",token];
NSDictionary *params = #{#"lang": #"en",#"content_id":contentId,#"project_id":[defaults objectForKey:#"project_id"]};
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:header forHTTPHeaderField:#"Authorization"];
[manager POST:#"http://example.com/api/project/delete-content" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"JSON: %#", responseObject);
if ([[responseObject objectForKey:#"result"] isEqualToString:#"success"]){
#try{
[selecedCellsArray removeObject:[NSString stringWithFormat:#"%ld",(long)pathRow]];
loadCount--;
if (loadCount==0){ //only there remove items from collectionview
// Delete the items from the data source.
[self deleteItemsFromDataSourceAtIndexPaths:selectedItemsIndexPaths];
// Now delete the items from the collection view.
[sortMediaCollection deleteItemsAtIndexPaths:selectedItemsIndexPaths];
[selectedPhotosURL removeAllObjects];
}
} #catch (NSException *e){
NSLog(#"something is bad %#",e);
[SVProgressHUD dismiss];
if (smArray.count<pathRow-1){
[smArray removeObjectAtIndex:(unsigned int)pathRow-1];
}
} #finally {
cell.selectedBG.hidden = YES;
[sortMediaCollection reloadSections:[NSIndexSet indexSetWithIndex:0]];
}
} else {
NSLog(#"can't delete photo!");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"Error: %#", error);
errorEndSpinner
}];
}
}
Hope this will be helpful for somebody.
I was getting the same error but found that it had to do with a different class having a mirrored copy of the array, and that class accessing a deleted index.
You can add an Exception Breakpoint to see exactly where the exception is coming from. Useful for differentiating errors in your code with errors coming from the iOS SDK: NSRangeException when deleting last UICollectionViewCell

IOS How to sync multithreading NSManagedObjectContext?

Application must update data from WebService in loop each 10 sec in background and display data to user by his request in the main thread. Also I need update and delete records by user request.
Updates done with runloop.
I have registered notification in the AppDelegate
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(contextChanged:) name:NSManagedObjectContextDidSaveNotification object:nil];
- (void)contextChanged:(NSNotification*)notification
{
if ([notification object] == [self managedObjectContext]) return;
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:#selector(contextChanged:) withObject:notification waitUntilDone:YES];
return;
}
[[self managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];
[self saveContext]; //do I need this here or marge save data too?
}
I have Storage sharedInstance class with
NSOperationQueue* operationQueue;
then inserts,updates,selects operators added this way from any thread:
-(void)do_something
{
[self.operationQueue addOperationWithBlock:^{
NSManagedObjectContext*moc; //creating new NSManagedObjectContext with AppDelegate.persistentStoreCoordinator
//do my staff
[moc save:&error]
}]
}
The problem is when I try update entities with #"my_id=%#", #(my_id)
[moc countForFetchRequest:fetchRequest error:&error]
return 0 and cause inserting of duplicate exists entity
The problem is with synchronization.
Advice please.
should I use instance of dispatch_queue_create("com.my.", 0); instead for each CoreData operation?
I did try remove operationQuiue
-(void)query:(void(^)(NSManagedObjectContext *context))queryBlock
{
NSLog(#"query CALL");
__block NSManagedObjectContext *context;
//if remove dispatch_sync and/or run in main thread result the same
dispatch_sync( dispatch_queue_create("com.myapp.db-queue", 0), ^{
AppDelegate*app = AppDelegate();
//same result if I use
//app.persistentStoreCoordinator or
//[app.managedObjectContext persistentStoreCoordinator]
NSPersistentStoreCoordinator *persistentStoreCoordinator= [app.managedObjectContext persistentStoreCoordinator];
context = [NSManagedObjectContext new];
[context setPersistentStoreCoordinator:persistentStoreCoordinator];
[context setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
queryBlock(context);
if ([context hasChanges])
{
NSError*err;
[context save:&err];
if (err) {
NSLog(#"context save: %#",[err localizedDescription]);
}
}
});
}
and call it as :
CoreStorage* cs = [CoreStorage sharedInstance];
NSArray* list = [ws GetSections]; //array of NSDictionaries
//if add this to operationQuiue resunt the same
[cs query:^(NSManagedObjectContext *moc) {
NSLog(#"START");
for (NSDictionary *section in list) {
NSNumber* Id= #([[section objectForKey:#"section_id"] integerValue]);
NSFetchRequest * fetchRequest = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Section" inManagedObjectContext: moc];
[fetchRequest setEntity:entity];
[fetchRequest setFetchLimit:1];
[fetchRequest setIncludesSubentities:NO];
[fetchRequest setPredicate: [NSPredicate predicateWithFormat:#"section_id=%#",Id]];
NSError *error =nil;
Section *entry;
if ([moc countForFetchRequest:fetchRequest error:&error] >0)
{
entry = [moc executeFetchRequest:fetchRequest error:nil][0];
NSLog(#"exist"); //this never call
}
else
{
entry = [NSEntityDescription insertNewObjectForEntityForName:#"Section" inManagedObjectContext:moc];
NSLog(#"NEW");
}
entry.section_id = Id;
entry.timeStamp = [NSDate date];
}
}];
Any sugastions please?
The problem is probably in the operation queue. You haven't configured it with max concurrent operations to be 1, right? In this case it is not serial, and operations that you add to it run concurrently. So here what happens. First operation fetches for the count of object with some ID, doesn't find it and creates one. At some point before it saves, another operation is added. This second operation fetches for the object with the same ID, doesn't find it and creates one. Then the first operation saves, then the second one saves, and you have a duplicate.
So try to make your operation queue serial [operationQueue maxConcurrentOperationCount:1];.
And no, you don't have to save after calling merge method of the managed object context.

assign value from NSDictionary to NSManagedObject

My app requires to get data from a .Net WCF service when the device is connected to WiFi.If there's a new row added on the server,it should add it to its CoreData database. I am using a NSDictionary for comparing the local objects with the remote objects. The code is:
-(void)handleGetAllCategories:(id)value
{
if([value isKindOfClass:[NSError class]])
{
NSLog(#"This is an error %#",value);
return;
}
if([value isKindOfClass:[SoapFault class]])
{
NSLog(#"this is a soap fault %#",value);
return;
}
NSMutableArray *result = (NSMutableArray*)value;
NSMutableArray *remoteObj = [[NSMutableArray alloc]init];
for (int i = 0; i < [result count]; i++)
{
EDVCategory *catObj = [[EDVCategory alloc]init];
catObj = [result objectAtIndex:i];
[remoteObj addObject:catObj];
}
NSArray *remoteIDs = [remoteObj valueForKey:#"categoryId"];
NSFetchRequest *request = [[[NSFetchRequest alloc] init]autorelease];
request.predicate = [NSPredicate predicateWithFormat:#"categoryId IN %#", remoteIDs];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Categories" inManagedObjectContext:__managedObjectContext];
[request setEntity:entity];
NSMutableArray *results = [[NSMutableArray alloc]initWithArray:[__managedObjectContext executeFetchRequest:request error:nil]];
NSArray *existingIDs = [results valueForKey:#"categoryId"];
NSDictionary *existingObjects = [NSDictionary dictionaryWithObjects:results forKeys:existingIDs];
for (NSDictionary *remoteObjectDic in remoteObj)
{
Categories *existingObject = [existingObjects objectForKey:[remoteObjectDic valueForKey:#"categoryId"]];
if (existingObject)
{
NSLog(#"object exists");
}
else
{
NSLog(#"create new local object");
// Categories *newCategory;
// newCategory = [NSEntityDescription insertNewObjectForEntityForName:#"Categories" inManagedObjectContext:__managedObjectContext];
// [newCategory setCategoryId:[NSNumber numberWithInt:[[remoteObjectDic objectForKey:#"categoryId"]intValue]]];
// [newCategory setCategoryName:[remoteObjectDic objectForKey:#"categoryName"]];
// [newCategory setDocCount:[NSNumber numberWithInt:[[remoteObjectDic objectForKey:#"docCount"]intValue]]];
// [newCategory setCategoryType:[NSNumber numberWithInt:[[remoteObjectDic objectForKey:#"categoryType"]intValue]]];
// [newCategory setSubCategoryId:[NSNumber numberWithInt:[[remoteObjectDic objectForKey:#"subCategoryId"]intValue]]];
// [__managedObjectContext insertObject:newCategory];
}
}
[my_table reloadData];
}
The problem is,I am not able to extract values from the remote object and assign it to the NSManagedObject.I have commented the code which (according to me) should save the values in new object to the managed object. Can someone please help me achieve this?
Thanks
Here is an example of a save I did in a recent project. I have somethings in wrappers so fetching a managed object and saving look a little weird on my end. Really the only major difference I see is the act of saving. Are you saving the new NSManagedObject elsewhere in the code?
dict = (NSDictionary*)data;
#try {
if (dict) {
CaretakerInfo* info = [GenericDataService makeObjectWithEntityName:NSStringFromClass([CaretakerInfo class])];
[info setName:[dict valueForKey:#"name"]];
[info setImageURL:[dict valueForKey:#"photo"]];
[info setCaretakerID:[dict valueForKey:#"id"]];
[GenericDataService save];
}
else {
theError = [Error createErrorMessage:#"No Data" Code:-42];
}
}
#catch (NSException *exception) {
//return an error if an exception
theError = [Error createErrorMessage:#"Exception Thrown While Parsing" Code:-42];
}
If not it should looks something like this...
NSError *error = nil;
[context save:&error];
If you have anymore information about what's happening when you extract or assigning data that would be helpful (error/warning/log messages).

save records from WCF service in CoreData

I am new to iOS development and CoreData too. I am calling a .Net WCF service for displaying data in a UITableViewcontroller in my app.I am saving this data in CoreData. When I add a new record on the server,I want it to get displayed in the UITableViewController as well as saved in CoreData.But this doesnt happen.I have to do a "Reset Contents and Settings" on the Simulator and then run the application again. When I do this,the app displays the latest records from the service.It also saves the new record in CoreData.I am using SUDZC for interacting with the wcf service.The code for calling the service,displaying data in UITableViewController and saving it to CoreData looks like this:
- (void)viewDidLoad
{
[super viewDidLoad];
self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
[my_table setDataSource:self];
[my_table setDelegate:self];
EDViPadDocSyncService *service = [[EDViPadDocSyncService alloc]init];
[service getAllCategories:self action:#selector(handleGetAllCategories:)];
}
-(void)handleGetAllCategories:(id)value
{
if([value isKindOfClass:[NSError class]])
{
NSLog(#"This is an error %#",value);
return;
}
if([value isKindOfClass:[SoapFault class]])
{
NSLog(#"this is a soap fault %#",value);
return;
}
NSMutableArray *result = (NSMutableArray*)value;
self.myData = [[NSMutableArray array] init];//array for storing 'category name'
self.catId = [[NSMutableArray array]init];//array for storing 'category ID'
self.myData=[self getCategories];
/*store data in Core Data - START*/
NSMutableArray *coreDataCategoryarray = [[NSMutableArray alloc]init];
NSManagedObjectContext *context = [self managedObjectContext];
Categories *newCategory;//this is the CoreData 'Category' object
for(int j=0;j<[result count];j++)
{
EDVCategory *edvCat = [[EDVCategory alloc]init];//this is the SUDZC 'Category' object
edvCat = [result objectAtIndex:j];
if ([self.catId count]>0) {
for (int i=0; i<[self.catId count]; i++) {
if ([edvCat categoryId] == [[self.catId objectAtIndex:i] integerValue]) {
checkFlag=TRUE;
}
}
}
if (checkFlag == FALSE) {
newCategory = [NSEntityDescription insertNewObjectForEntityForName:#"Categories" inManagedObjectContext:context];
[newCategory setCategoryId:[NSNumber numberWithInt:[edvCat categoryId]]];
[newCategory setCategoryName:edvCat.categoryName];
[newCategory setDocCount:[NSNumber numberWithInt:[edvCat docCount]]];
[newCategory setCategoryType:[NSNumber numberWithShort:[edvCat categoryType]]];
[newCategory setSubCategoryId:[NSNumber numberWithInt:[edvCat subCategoryId]]];
[coreDataCategoryarray addObject:newCategory];
}
}
/*store data in Core Data - END*/
NSError *error = nil;
if (![context save:&error])
{
[coreDataCategoryarray release];
}
else
{
//return [coreDataCategoryarray autorelease];
[coreDataCategoryarray autorelease];
}
self.myData=[self getCategories];
[my_table reloadData];
}
-(NSMutableArray *)getCategories
{
NSFetchRequest *request = [[[NSFetchRequest alloc] init]autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Categories" inManagedObjectContext:__managedObjectContext];
NSSortDescriptor *sortByName = [[[NSSortDescriptor alloc] initWithKey:#"categoryId" ascending:YES] autorelease];
[request setSortDescriptors:[NSArray arrayWithObject:sortByName]];
[request setEntity:entity];
entity = nil;
NSError *error = nil;
NSMutableArray *fetchResults = [[__managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
[request setReturnsObjectsAsFaults:NO];
NSManagedObject *aTabrss;
NSMutableArray *arForGetCategory=[[NSMutableArray alloc]init];
for (aTabrss in fetchResults){
[arForGetCategory addObject:[aTabrss valueForKey:#"categoryName"]];
[self.catId addObject:[aTabrss valueForKey:#"categoryId"]];
}
return (arForGetCategory);
}
What changes should I make in my code so that it reflects the latest data from the service and saves it to CoreData(sqlite) at the same time?
It seems like the class that you really need is NSUserDefaults:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsuserdefaults_Class/Reference/Reference.html

Method/IBAction stuck in infinite loop. Still no success

Now this may sound like my earlier problem/question but I've changed and tried a few things that were answered in my other questions to try to make it work, but I've still got the same problem.
I am observing a core data property from within a NSManagedObject sub-class and the method that gets called when the property changes calls another method but in this method it adds Core Data objects which triggers the KVO method which triggers the method again and so forth. Or so it seems, I'm not too sure about that because something different seems to happen, here is the series of events …
I click a button syncing with iCal (this in an IBAction with the exact same code thats in the method syncKVO). This sync works fine.
I add an object to my outline view. All is well.
I change its name which triggers the KVO Declaration (because I changed the 'name' property) which syncs with iCal. Works fine.
I delete the object I just added and somehow it triggers the KVO declaration (thus triggering the method) and puts me into an infinite loop.
Now for some code.
Code inside the NSManagedObject Subclass (called JGManagedObject) …
- (void) awakeFromFetch {
[self addObserver:[NSApp delegate] forKeyPath:#"name" options:0 context:nil];
}
- (void) awakeFromInsert {
[self addObserver:[NSApp delegate] forKeyPath:#"name" options:0 context:nil];
}
+ (void) addObserver{
[self addObserver:[NSApp delegate] forKeyPath:#"name" options:0 context:nil];
}
+ (void) removeObserver{
[self removeObserver:[NSApp delegate] forKeyPath:#"name"];
}
The KVO Declaration (inside the App Delegate) …
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:#"name"]) {
[self performSelector:#selector(syncKVO:)];
}
}
The Method (also inside the App Delegate)…
- (void)syncKVO:(id)sender {
NSManagedObjectContext *moc = [self managedObjectContext];
[syncButton setTitle:#"Syncing..."];
NSString *dateText = (#"Last Sync : %d", [NSDate date]);
[syncDate setStringValue:dateText];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:#"projects" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
NSAlert *anAlert = [NSAlert alertWithError:error];
[anAlert runModal];
}
NSArray *namesArray = [array valueForKey:#"name"];
NSPredicate *predicate = [CalCalendarStore taskPredicateWithCalendars:[[CalCalendarStore defaultCalendarStore] calendars]];
NSArray *tasksNo = [[CalCalendarStore defaultCalendarStore] tasksWithPredicate:predicate];
NSArray *tasks = [tasksNo valueForKey:#"title"];
NSMutableArray *namesNewArray = [NSMutableArray arrayWithArray:namesArray];
[namesNewArray removeObjectsInArray:tasks];
NSLog(#"%d", [namesNewArray count]);
NSInteger *popIndex = [calenderPopup indexOfSelectedItem];
//Load the array
CalCalendarStore *store = [CalCalendarStore defaultCalendarStore];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *supportDirectory = [paths objectAtIndex:0];
NSString *fileName = [supportDirectory stringByAppendingPathComponent:#"oldtasks.plist"];
NSMutableArray *oldTasks = [[NSMutableArray alloc] initWithContentsOfFile:fileName];
[oldTasks removeObjectsInArray:namesArray];
NSLog(#"%d",[oldTasks count]);
//Use the content
NSPredicate* taskPredicate = [CalCalendarStore taskPredicateWithCalendars:[[CalCalendarStore defaultCalendarStore] calendars]];
NSArray* allTasks = [[CalCalendarStore defaultCalendarStore] tasksWithPredicate:taskPredicate];
// Get the calendar
CalCalendar *calendar = [[store calendars] objectAtIndex:popIndex];
// Note: you can change which calendar you're adding to by changing the index or by
// using CalCalendarStore's -calendarWithUID: method
// Loop, adding tasks
for(NSString *title in namesNewArray) {
// Create task
CalTask *task = [CalTask task];
task.title = title;
task.calendar = calendar;
// Save task
if(![[CalCalendarStore defaultCalendarStore] saveTask:task error:&error]) {
NSLog(#"Error");
// Diagnostic error handling
NSAlert *anAlert = [NSAlert alertWithError:error];
[anAlert runModal];
}
}
NSMutableArray *tasksNewArray = [NSMutableArray arrayWithArray:tasks];
[tasksNewArray removeObjectsInArray:namesArray];
NSLog(#"%d", [tasksNewArray count]);
for(NSString *title in tasksNewArray) {
NSManagedObjectContext *moc = [self managedObjectContext];
JGManagedObject *theParent =
[NSEntityDescription insertNewObjectForEntityForName:#"projects"
inManagedObjectContext:moc];
[theParent setValue:nil forKey:#"parent"];
// This is where you add the title from the string array
[theParent setValue:title forKey:#"name"];
[theParent setValue:[NSNumber numberWithInt:0] forKey:#"position"];
}
for(CalTask* task in allTasks)
if([oldTasks containsObject:task.title]) {
[store removeTask:task error:nil];
}
// Create a predicate for an array of names.
NSPredicate *mocPredicate = [NSPredicate predicateWithFormat:#"name IN %#", oldTasks];
[request setPredicate:mocPredicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
// Execute the fetch request put the results into array
NSArray *resultArray = [moc executeFetchRequest:request error:&error];
if (resultArray == nil)
{
// Diagnostic error handling
NSAlert *anAlert = [NSAlert alertWithError:error];
[anAlert runModal];
}
// Enumerate through the array deleting each object.
// WARNING, this will delete everything in the array, so you may want to put more checks in before doing this.
for (JGManagedObject *objectToDelete in resultArray ) {
// Delete the object.
[moc deleteObject:objectToDelete];
}
//Save the array
[namesArray writeToFile:fileName atomically:YES];
[syncButton setTitle:#"Sync Now"];
NSLog(#"Sync Completed");
}
What I've tried …
Filtering the Keypaths that call the KVO Declaration with
if ([keyPath isEqualToString:#"name"]) {
…
}
Detaching and reattaching observers with
[JGManagedObject removeObserver];
//and
[JGManagedObject addObserver];
but with that it works the first time but stops the method the second time saying that it cannot remove the observer because it is not observing, which doesn't make sense because I added the observer again the first time. That is why I left this code out of the actual method else it would stop on the second sync.
I'm not sure whats going on with this, I think I've tried everything. Whats gone wrong?
Any help would be greatly appreciated.
The problem might be here:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:#"name"]) {
[self performSelector:#selector(syncKVO:)];
}
}
You call syncKVO: everytime something happens to 'name' regardless of what it is that has actually happened to 'name'. I suggest you start using the object, change and context parameters to determine what has just happened and what action, if any, should be undertaken.
BTW, it's not considered good practice to add a lot of stuff to the app delegate. You might want to put all this syncing stuff into a proper controller class and call [NSApp delegate] when you need it.