How to convert dictionary data to NSManagedObject data?
I used propertiesToFetch, and it returns dictionary data. But I want NSManagedObject data.
please guide me
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:catalogID, pageID, nil]];
[fetch setResultType:NSDictionaryResultType];
[fetch setReturnsDistinctResults : YES];
NSError* error = nil;
self.resultPageArray = [context executeFetchRequest:fetch error:&error];
When I changed the type to NSManagedObjectResultType, then I got non-distinct data. I read that while using propertiesToFetch it saves the data in dictionary format. But I want to get the distinct data and save it into the NSManagedObjects
Try This,
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:catalogID, pageID, nil]];
[fetch setResultType:NSManagedObjectResultType];
[fetch setReturnsDistinctResults : YES];
NSError* error = nil;
self.resultPageArray = [context executeFetchRequest:fetch error:&error];
My code :
NSError *error = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"BookInfo"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setPropertiesToFetch:#[catalogID, pageID]];
[fetchRequest setPredicate: [NSPredicate predicateWithFormat:#"(bookId == %#)",strId]];
NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if( fetchedItems.count > 0 ) {
BookInfo *bInfo = [fetchedItems lastObject];
NSLog(#"%#",bInfo.bookName);
}
I have solved the issue. I was fetching the data of NSManagedObjects. After that I saved that data to the other array without repetition. And return the new array.
self.resultPageArray = [context executeFetchRequest:fetch error:&error];
NSMutableArray *resultantFinalArr = [[NSMutableArray alloc] init];
for (int i = 0; i<resultPageArray.count; i++)
{
catalogPageDataModel *atIndexI = [resultPageArray objectAtIndex:i];
BOOL find = NO;
for (catalogPageDataModel* catalogPageDataModel in resultantFinalArr)
{
if (catalogPageDataModel.pageid.intValue == atIndexI.pageid.intValue)
{
find = YES;
break;
}
}
if (!find)
[resultantFinalArr addObject:atIndexI];
}
NSLog(#"result array count %lu",(unsigned long)resultantFinalArr.count);
NSLog (#"names: %#",resultantFinalArr);
return resultantFinalArr;
Related
I have stored dictionary in the transformable attribute.I want to know
How to get single data from it?**
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]
initWithEntityName:#"MemberProfile"];
NSSortDescriptor *ordering = [[NSSortDescriptor alloc] initWithKey:
[member.member_Profile objectForKey:"#order"] ascending:YES];
[fetchRequest setSortDescriptors:[NSArray
arrayWithObjects:ordering,nil]];
NSArray *result = [self.managedObjectContext
executeFetchRequest:fetchRequest error:Nil];
self.masterList = [[NSMutableArray alloc] initWithArray:result];
Import NSManagedObject(InstallProject) and fetch one object like this,
-(InstallProject *)readSelectedInstall:(NSString *)projIDString
{
NSArray *fetchedObjects;
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"InstallProject" inManagedObjectContext: context];
[fetch setEntity:entityDescription];
[fetch setPredicate:[NSPredicate predicateWithFormat:#"(ANY ProjID contains[cd] %#)",projIDString]];
NSError * error = nil;
fetchedObjects = [context executeFetchRequest:fetch error:&error];
if([fetchedObjects count] == 1)
return [fetchedObjects objectAtIndex:0];
else
return nil;
}
I have created a an entity called Statutory with four columns namely name,complianceName,statMappingName,country
i want a get all complianceName names that matches a specific statMappingName. Following is my code
NSString *nameToGet = self.statNameArray[indexPath.row] ;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"complianceName = %#", nameToGet];
[fetch setPredicate:predicate];
NSLog(#"n %#",predicate);
NSError *error = nil;
NSArray *results = [[self managedObjectContext] executeFetchRequest:fetch error:&error];
if(results) {
NSLog(#"Entities with that name: %#", results);
} else {
NSLog(#"Error: %#", error);
}
But it is not providing the compliance name specific to that statMappingName. How can I be able to get all complianceName that has a specific statMappingName?
Try this:-
NSString *firstName = statMappingName;
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"firstName == %#", firstName]];
If you want to fetch specific column from core data
You can use the below method:-
NSEntityDescription *entity = [NSEntityDescription entityForName:entityname inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setReturnsObjectsAsFaults:NO];
[request setEntity:entity];
[request setFetchLimit:1];
[request setPredicate:[NSPredicate predicateWithFormat:#"(complianceName LIKE %#)",nametoGet]];
NSError *error = nil;
NSMutableArray *tempDataArr = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
Note:-
*entityname: Your entity name
*self.managedObjectContext : Your managedobjectcontext
To Get All compliance Name use the below method
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:entityName];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSMutableArray *tempDataArr =[NSMutableArray new];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"(ANY complianceName LIKE %#)",nametoGet]];
tempDataArr = [[self.managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
try these code for contains statMappingName
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"complianceName contains[c] %#", statMappingName];
Even though I don't have more than 3 records in my table , and a single table. Method : executeFetchRequest takes too long
loanIDArray=[[NSMutableArray alloc]init];
appDelegate=[[UIApplication sharedApplication] delegate];
context=[appDelegate managedObjectContext];
entityDesc=[NSEntityDescription entityForName:#"Personal_Info" inManagedObjectContext:context];
NSFetchRequest* request=[[NSFetchRequest alloc]init];
[request setEntity:entityDesc];
NSPredicate* predicate=[NSPredicate predicateWithFormat:#"status_of_form==%#",#"Completed"];
[request setPredicate:predicate];
NSError* fetchError;
NSError* error;
This line takes too long
NSArray* objects = [context executeFetchRequest:request error:&fetchError];
if (!fetchError) {
for (NSManagedObject* obj in objects) {
[loanIDArray addObject:[obj valueForKey:#"app_id"]];
}
}
else
NSLog(#"Status Fetch Error : %#",fetchError.description);
[context save:&error];
if (!error)
NSLog(#"count : %d",loanIDArray.count );
else
NSLog(#"error : %#",error.description);
try replace this code:
if (!fetchError) {
for (NSManagedObject* obj in objects) {
[loanIDArray addObject:[obj valueForKey:#"app_id"]];
}
}
with this to avoid iteration:
if (!fetchError) {
loanIDArray = [objects valueForKeyPath:#"app_id"];
}
Try this.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
[fetchRequest setEntity:entityDesc];
NSError *error = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"status_of_form==%#",#"Completed"];
[fetchRequest setPredicate:predicate];
NSArray *request = [context executeFetchRequest:fetchRequest error:&error];
if (!request.count==0) {
for (int i = 0; i<=request.count-1;i++) {
NSManagedObject *obj = [request objectAtIndex:i];
[loanIDArray addObject:[obj valueForKey:#"app_id"]];
}
}
I save to core data and load all messages with code below, but how can I load only messages for 2 users, for self user and for destination user, I want base it on user JID.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [[self appDelegate].xmppMessageArchivingCoreDataStorage mainThreadManagedObjectContext];
NSEntityDescription *messageEntity = [NSEntityDescription entityForName:#"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:context];
fetchRequest.entity = messageEntity;
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"timestamp" ascending:YES];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:fetchRequest error:&error];
//Now you get the NSArray with element type of "XMPPMessageArchiving_Message_CoreDataObject"
assuming your message objects have a from relationshit to a User entity.
As simple as adding (before executing the request):
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"from = %# OR from = %#",selfUser,otherUser];
Where selfUser and otherUser are User core data managed objects or managed object IDs of users.
if you use a field identifier (highly not recomended):
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"bareJID.bare = %# OR bareJID.bare = %#",selfUser.jid,otherUser.jid];
You might want to read THIS
I have used following method and it worked correctly :)
-(void)checkForPastMessageAndDisplayIt
{
NSString *strmyid = #"user1#domain";
NSString *strBuddy = #"user2#domain";
NSManagedObjectContext *moc = [[self appDelegate] managedObjectContext_message_achiving];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"XMPPMessageArchiving_Message_CoreDataObject"
inManagedObjectContext:moc];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"bareJidStr = %# OR bareJidStr = %#", strmyid, strBuddy];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *messagesArray = [moc executeFetchRequest:fetchRequest error:&error];
[messagesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id messageObject = [messagesArray objectAtIndex:idx];
if ([messageObject isKindOfClass:[XMPPMessageArchiving_Message_CoreDataObject class]]) {
XMPPMessageArchiving_Message_CoreDataObject *currentMessageCoreDataObject = (XMPPMessageArchiving_Message_CoreDataObject*)messageObject;
XMPPMessage *message = currentMessageCoreDataObject.message;
if (message!=nil) {
[messages addObject:message];
}
}
}];
}
You can use like that
-(void)testMessageArchiving {
NSString *strmyid = #"myid";
NSString *strBuddy ="toid";
NSLog(#"my id and buddy is is %# and %#",strmyid,strBuddy);
XMPPMessageArchivingCoreDataStorage *storage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"XMPPMessageArchiving_Message_CoreDataObject"
inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
request.predicate = [NSPredicate predicateWithFormat:#"bareJidStr = %# OR bareJidStr = %#", strmyid, strBuddy];
NSError *error;
NSArray *messages = [moc executeFetchRequest:request error:&error];
// NSLog(#"the history of messages is %#",messages);
[self print:[[NSMutableArray alloc]initWithArray:messages]];
I am having some difficulties in deleting an entry from Core Data.
It works but the NSManagedObject data has no values (fault), and so sometimes the wrong entry will be deleted.
In my deleteWholeDatabase method the objects are filled with values.
And in the deleteEntryFromDatabase method are no values. But why?
Here are my methods:
-(NSArray*)databaseRequest{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:currentEntity inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSError *error;
NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
return items;
}
-(void)deleteWholeDatabase{
for (NSManagedObject *objectToDelete in [self databaseRequest]) {
[managedObjectContext deleteObject:objectToDelete];
NSLog(#"%# object deleted",objectToDelete);
}
[self saveContext];
NSLog(#"All entries deleted!");
}
-(void)deleteEntryFromDatabase:(NSManagedObjectContext*)context forEntry:(NSIndexPath*)indexPath{
NSManagedObject *objectToDelete=[[self databaseRequest] objectAtIndex:indexPath.row];
[managedObjectContext deleteObject:[managedObjectContext objectWithID:[objectToDelete objectID]]];
[self saveContext];
NSLog(#"%# deleted!",[managedObjectContext objectWithID:[objectToDelete objectID]]);
}
The wrong entry is being deleted because each request return the itens in a different order. Try deleting the intens by comparing their memory adress
Instead of keeping a calling [self databaseRequest] everywhere, I would keep a local copy of NSManagedObjectID's as an array.
- (void)init {
self.entities = [self databaseRequest];
}
-(NSArray*)databaseRequest{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:currentEntity inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSError *error;
NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSMutableArray *itemIDs = [[NSMutableArray alloc] initWithCapacity:[items count]];
for (NSManangedObject *item in items) {
[itemIDs addObject:[item objectID]];
}
return items;
}
Then everywhere where you call [self databaseRequest], you will get an have the correct NSManagedObjectID. Then you just need to get the correct entity from the ID.