How to read NSArray from coredata entity - ios

I am trying to read a coredata entity into a NSMutableArray however I keep getting back weird lots of data. For instance when I get back an NSDictionary of values it looks like this
data: {
companyName = "WPremium";
desc = "Test";
guid = "Otq12342";
install = (
"0x1e59e910 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p851>",
"0x1e59e8e0 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p848>",
"0x1e59e830 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p837>",
"0x1e59e930 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p853>",
"0x1e59e850 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p839>",
"0x1e59e890 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p843>",
"0x1e59e8b0 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p845>",
"0x1e59e7c0 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p830>",
"0x1e5957e0 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p829>",
"0x1e59e810 <x-coredata://BAF7B1AD-F357-455A-B9D7-1288F7D1F652/Install/p835>",
"(...and 16 more...)"
);
I would like to know how to put the install object of the coredata dictionary into an NSArray so I can sort it.
Update: this is how I call my coredata object.
- (NSMutableArray *)readSelectedInstall:(NSString *)projIDString {
NSManagedObjectContext *context = [self managedObjectContext];
if (context == nil) {
NSLog(#"Nil");
}
else {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"InstallProject" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"projID==%#",projIDString];
[fetchRequest setPredicate:predicate];
NSError *error;
NSMutableArray *installProjectDictionaryArray = [[NSMutableArray alloc] init];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (InstallProject *installProj in fetchedObjects) {
NSMutableDictionary *tempInstallProjectDictionaryArray = [[ NSMutableDictionary alloc] init];
[tempInstallProjectDictionaryArray setObject:installProj.companyName forKey:#"CompanyName"];
[tempInstallProjectDictionaryArray setObject:installProj.projNo forKey:#"ProjNo"];
[tempInstallProjectDictionaryArray setObject:installProj.desc forKey:#"Desc"];
[tempInstallProjectDictionaryArray setObject:installProj.guid forKey:#"GUID"];
[tempInstallProjectDictionaryArray setObject:installProj.projID forKey:#"ProjID"];
[tempInstallProjectDictionaryArray setObject:installProj.install forKey:#"install"];
[installProjectDictionaryArray addObject:tempInstallProjectDictionaryArray];
}
return installProjectDictionaryArray;
}
return nil;
}
then with the returning NSMutableArray I do this
NSMutableArray *getarray = [self readSelectedInstall:projIDString];
NSMutableDictionary *installsDictionary = [getarray objectAtIndex:0];
NSMutableArray *tempInstalls = [installsDictionary objectForKey:#"install"];
NSLog(#"%#", tempInstalls);
NSArray *tempSortedItemsArray = [tempInstalls sortedArrayUsingDescriptors:
#[[NSSortDescriptor
sortDescriptorWithKey:#"dp" ascending:YES],
[NSSortDescriptor
sortDescriptorWithKey:#"dc
" ascending:YES]]];
tempInstalls = [tempSortedItemsArray mutableCopy];
tempSortedItemsArray = nil;
NSLog(#"%#", tempInstalls);
but on that last line of code is where I have the weird output.

All you need to do is fetch the core data NSManagedObject from Core Data, install would be returned as an NSSet, by the looks of things it is an NSSet of NSManagedObjects.
Once you have the object you access the "install" property and sort however you want.
// Get the Core Data Object (Uses Magical Record)
MyObject *object = [MyObject MR_findFirstWithPredicate:[NSPredicate objectPredicate:self.users_id]];
// Sort the object set into an array
NSArray *installs = [object.install sortedArrayUsingDescriptors:#[ [NSSortDescriptor sortDescriptorWithKey:k_timestamp ascending:YES] ]];

Related

How to get single attribute Value of entity in Coredata?

I am having Entity Called EY_Appliances with Attributes applianceId ,applianceName,watts,amountPerWatts.Also i am Having Arrays like this:
Prefrence.h
#define APPLIANCENAME_ARRAY #[#"Fridge",#"Microwave",#"Mixie",#"Roti Maker",#"Coffee Machine",#"Dish Washer",#"Wet Grinder",#"Electric Stove",#"Ceiling Fan",#"TV",#"Table Fan",#"Tubelight",#"Bulb",#"AC",#"Vacuum Cleaner",#"CFL",#"LED",#"Washing Machine",#"Toaster",#"Room Heater",#"Iron",#"Motor",#"Water Heater",#"Inverter / UPS",#"Air Cooler",#"Steamer / Air Fryer",#"Hair Dryer",#"Laptop",#"PC",#"Tablet",#"Router / Modem",#"Home Theatre",#"Projector",#"PS3/PS4/XBOX"]
#define WATTS_ARRAY #[#"120",#"1000",#"700",#"30",#"167",#"810",#"180",#"150",#"75",#"120",#"75",#"40",#"60",#"1200",#"1400",#"20",#"6",#"300",#"1000",#"1600",#"1400",#"2400",#"1000",#"67",#"173",#"585",#"1026",#"15",#"150",#"4",#"4",#"17",#"240",#"10"]
DataAccessHandler.m
-(void)storeApplianceDetailsToEntity
{
NSManagedObjectContext *context = [self managedObjectContext];
for (int i=0; i<APPLIANCENAME_ARRAY.count; i++)
{
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"EY_Appliances" inManagedObjectContext:context];
[object setValue: APPLIANCENAME_ARRAY[i] forKey:#"applianceId"];
[object setValue: APPLIANCENAME_ARRAY[i] forKey:#"applianceName"];
[object setValue: WATTS_ARRAY[i] forKey:#"watts"];
[object setValue: WATTS_ARRAY[i] forKey:#"amountPerWatts"];
}
NSError *error = nil;
if (![context save:&error])
{
NSLog(#"Saving Failed with error %#", error);
}
NSLog(#"entityValue==>%#",context);
}
-(NSArray *) fetchApplianceDetailsFromEntity:(NSString *) entityName
{
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest;
NSEntityDescription *entityDescription;
NSArray *array;
fetchRequest = [[NSFetchRequest alloc] init];
entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entityDescription];
array = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSLog(#"arr==>>%#",array);
return array;
}
ViewController.m
-(void)viewDidLoad
{
DataAccessHandler *dataAccess=[[DataAccessHandler alloc]init];
[dataAccess storeApplianceDetailsToEntity];
NSArray *applianceData = [dataAccess fetchApplianceDetailsFromEntity:#"EY_Appliances"];
//How to print the applianceName,If i write Like this applianceData.applianceName,it shows error…
}
1.How to print the applianceName?
2.How to set the applianceId primaryKey and store the value for applianceId 1 to 34?
NSDictionary *applianceData = [dataAccess fetchApplianceDetailsFromEntity:#"EY_Appliances"];
use keyword get back value
applianceData is an array, so you need to access it through an index
Your code just now is using the appliance name as ID - if all you need is an identifier, you can use your index i
The load returns everything into the array - if you only want to load part of the dataset, you need to add a fetch predicate in fetchApplianceDetailsFromEntity
[fetch setPredicate:[NSPredicate predicateWithFormat:#"(applianceId == %#)",idString]];

Get array of objects from core data

I am trying to adapt a method I was using to get a dictionary of ids from a core data request to an array of objects. However, I am getting confused about what array is the one I want. Basically, I want an array of contacts with all the appropriate attributes. Which array of contact objects in the following is the one I want, the fetchedObject or the tmpArray?
-(NSMutableArray *) getContactsNeedingSync
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [IDModel sharedInstance].managedObjectContext;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"needsync==#1"];
fetchRequest.predicate = predicate;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Contacts" inManagedObjectContext:context];
fetchRequest.entity = entity;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"cid" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
fetchRequest.sortDescriptors = sortDescriptors;
NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
NSArray *fetchedObjects = fetchedResultsController.fetchedObjects;
//is this the array I want?
NSInteger resultCount = [fetchedObjects count];
if (resultCount == 0) {
NSLog(#"result Count is zero");
return [NSMutableArray array];//nothing in the Core Data store
}
else {
Contacts *contact;
NSMutableArray *tmpArray = [NSMutableArray array];
int i;
for (i = 0; i < resultCount; i++) {
contact = fetchedObjects[i];
tmpArray[contact.cid] = contact;
}
return tmpArray;//is this array I want?
}
context = nil;
}
Your code creates a fetch request and sets it up to collect a sorted set of objects. You then use an NSFetchedResultsController to collect the results for the fetch request. You then have a bit of code which resorts the sorted data (init tmpArray).
You can simplify this by removing the NSFetchedResultsController and just executing the fetch request directly. The NSFetchedResultsController isn't helping you as you aren't adding a delegate to it or retaining it.
The data is also already sorted because of the NSSortDescriptor. Indeed, if it was't you'd get crashes as you'd be trying to insert into an array that wasn't big enough... So, remove tmpArray and the associated code.

How to select from core data with multiple filters?

From what I have found online it seemed as if this would be the way to select from core data on multiple values. I want to get everything from exercises where machineName = var1 or machineName = var2... For whatever reason nothing is returned after I debug past the executeFetchRequest selector and equiptmentData is empty. Also I do not get any errors. Any help or suggestions is much appreciated and thanks in advance.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Exercises" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSMutableArray *predicates = [[NSMutableArray alloc] init];
for(int i = 0; i < [checked count]; i++)
{
if([[checked objectAtIndex:i] boolValue] == YES)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"machineName == %#", itemArray[i]];
[predicates addObject: predicate];
}
}
NSArray *predicatesArray = [[NSArray alloc] initWithArray: predicates];
NSPredicate * compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates: predicatesArray];
fetchRequest.predicate = compoundPredicate;
NSError *error = nil;
NSArray *equiptmentData = [managedObjectContext executeFetchRequest:fetchRequest error: &error];
Turns out this is the right way to do this I was not inserting into core data properly

how to edit coredata value then save context to overwrite old values?

I am trying to edit a item in one of my coredata tables/entities. I am not 100% sure how to do this but I think its along these lines.
First you create the context, then fetchrequest the entity using a predicate to select the exact item from the table/entity. then save these values into the correct var type update the values then some how overwrite the existing item with the new values.
The last part is where I am stuck, this is the code I currently have:
- (void)editSelectedInstall:(NSString *)invGuid {
NSManagedObjectContext *context = [self managedObjectContext];
if (context == nil) {
NSLog(#"Nil");
}
else {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Install" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"invGUID==%#",invGuid];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *myArray = [context executeFetchRequest:fetchRequest error:&error];
NSMutableDictionary *myDictionary = [myArray objectAtIndex:0];
NSLog(#"%#", myDictionary);
// Here I will update the values & then save the context?
// For example I think I am to update the items like this:
myDictionary.num = #"1234";
myDictionary.name = #"new name";
}
}
I think I'm almost there I just need help saving the context so that it overwrites the previous values.
Try this:
//loop through result set and update as required
for (Install *temp in myArray) {
temp.num = #"1234";
temp.name = #"New name";
}
//save
[context save:&error];

Core Data returning NSArrays instead of NSStrings

For some reason all of the NSString typed attributes are being returned as NSArrays in my Article object. Here's my function to retrieve them:- (NSArray *)getSavedArticles
{
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
NSError *error = nil;
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Article" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSSortDescriptor *dateSort = [NSSortDescriptor sortDescriptorWithKey:#"last_opened" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:dateSort]];
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
return fetchedObjects;
}
I have not created a NSManagedObjectModel for these, and instead I'm just accessing them using KVO.
//self.data has the array returned from getSavedArticles
NSManagedObject *object = [self.data objectAtIndex:indexPath.row];
NSString *path = [object valueForKey:#"path"];
NSString* id = [object valueForKey:#"id"];
When I look at this in the variables pane, on path and id I see (__NSArrayI *) ... Variable is not a CFString. Printing the description of either of these also prints out the parenthesis used when printing arrays.
I'm just wondering if this could be due to the sort descriptor? I have double checked that the data going into these objects is typed correctly, and the SQLite database that I'm using to backup everything is displaying strings.
I have tried re-installing the app in the simulator, and resetting it. I still get a NSArray instead of a NSString.
I really don't know what's going on here. Any help would be appreciated.
EDIT: I just found something else interesting. I do another check to see if an Article has been saved, and this time I don't get a NSArray for the article path:- (NSString *)hasArticleSaved:(NSString *)id
{
NSString *path = nil;
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"%K == %#", #"id", id]];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Article" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects.count > 0) {
NSManagedObject *savedArticle = [fetchedObjects objectAtIndex:0];
path = [savedArticle valueForKey:#"path"];
}
return path;
}
Now I'm really confused. Any takers?
Your problem is here:
[self.data objectForKey:indexPath.row]
...because objectForKey: is looking for a string key name e.g. "path" or "id". Giving it an integer will produce an error or a random return.
Instead, you want:
[self.data objectAtIndex:indexPath.row]
... which will return the managed object at the given index in the array.
I found the issue. I had changed the data structure for my table so self.data is an array of arrays...and with only 1 object it looked like I was getting a NSArray back when in fact I was just accessing the data wrong. I just needed to do [[self.data objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

Resources