iOS How to auto release a method in viewDidLoad? - ios

I try to invoke this method for one time ever the apps is install and launch for the first time.
My idea is to fill the core data table with my data.
How to auto release this method in viewDidLoad?
- (void)insertNewObject:(id)sender
{
if ((firstRun!=YES)) {
NSLog(#"The data was already Added");
}
else {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:[[NSString alloc]initWithFormat:#"new"] forKey:#"name"];
firstRun = NO;
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}

You can use NSUserDefaults to verify if it's the first run.
- (void)insertNewObject:(id)sender
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSDictionary *userDefaultsDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], #"firstRun", nil];
[prefs registerDefaults:userDefaultsDefaults];
BOOL firstRun = [prefs boolForKey:#"firstRun"];
if (firstRun==YES) {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:[[NSString alloc]initWithFormat:#"new"] forKey:#"name"];
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[prefs setBool:NO forKey:#"firstRun"];
[prefs synchronize];
} else {
NSLog(#"The data was already Added");
}
}
You can call this method in your viewWillDisappear or viewDidLoad with [self insertNewObject:nil];

Related

coredata issue fetching data

I am getting only last record from coredata? below is the my code .
NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Company"
inManagedObjectContext:context];
[object setValue:#"infosys" forKey:#"cname"];
[object setValue:#"01" forKey:#"compID"];
[object setValue:#"Pune" forKey:#"locaation"];
[object setValue:#"wipro" forKey:#"cname"];
[object setValue:#"02" forKey:#"compID"];
[object setValue:#"Mumbai" forKey:#"locaation"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (result.count<=0) {
NSLog(#"No User Found");
}
else{
NSString *cname;
NSString *compID;
NSString *locaation;
for (NSManagedObject *obj in result) {
cname=[obj valueForKey:#"cname"];
compID=[obj valueForKey:#"compID"];
locaation=[obj valueForKey:#"locaation"];
}
NSLog(#"Store Data = %#",[NSString stringWithFormat:#"%# %# %#",cname,compID,locaation]);
}
Add objects like this,
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Company" inManagedObjectContext:context];
[object setValue:#"infosys" forKey:#"cname"];
[object setValue:#"01" forKey:#"compID"];
[object setValue:#"Pune" forKey:#"locaation"];
NSManagedObject *object2 = [NSEntityDescription insertNewObjectForEntityForName:#"Company" inManagedObjectContext:context];
[object2 setValue:#"wipro" forKey:#"cname"];
[object2 setValue:#"02" forKey:#"compID"];
[object2 setValue:#"Mumbai" forKey:#"locaation"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (result.count<=0) {
NSLog(#"No User Found");
}
else{
NSString *cname;
NSString *compID;
NSString *locaation;
for (NSManagedObject *obj in result) {
cname=[obj valueForKey:#"cname"];
compID=[obj valueForKey:#"compID"];
locaation=[obj valueForKey:#"locaation"];
NSLog(#"Store Data = %#",[NSString stringWithFormat:#"%# %# %#",cname,compID,locaation]);
}
}

How to add Array as string in Core Data in Objective c

I am new in iOS and I am facing problem regarding to add NSArray in Core Data as an NSString.
I am using code like this:
NSManagedObjectContext *context = [self managedObjectContext];
//Converting array as an string...
AuditIDCoreData=[NSString stringWithFormat:#"%#",idAuditarray];
AuditnameCoreData=[NSString stringWithFormat:#"%#",nameAuditarray];
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Get_Auditnames_User" inManagedObjectContext:context]];
// NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSLog(#"Result =%#",results);
NSString *Stringaudit =[NSString stringWithFormat:#"%#",idAuditarray];
ComplareArray=[devices valueForKey:#"auditname"];
ComplareArray2=[devices valueForKey:#"auditid"];
BOOL contains = [ComplareArray2 containsObject:Stringaudit];
if(contains == YES)
{
}
else
{
if (self.device) {
// Update existing device
[self.device setValue:AuditIDCoreData forKey:#"auditid"];
[self.device setValue:AuditnameCoreData forKey:#"auditname"];
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Get_Auditnames_User" inManagedObjectContext:context];
// NSLog(#"context",newDevice);
[newDevice setValue:AuditIDCoreData forKey:#"auditid"];
[newDevice setValue:AuditnameCoreData forKey:#"auditname"];
}
//NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
Code I have Updated:
NSString *FailString =#"";
NSString *WarningString =#"";
NSManagedObjectContext *context = [self managedObjectContext];
for (int i = 0; i < idarray.count; i++){
if (self.device) {
// Update existing device
[device setValue:Audit forKey:#"auditnameId"];
[device setValue:Passarray[i] forKey:#"checklistid"];
[device setValue:CheckpointNameIDArray[i] forKey:#"checkpointid"];
[device setValue:FailString forKey:#"failreason"];
[device setValue:WarningString forKey:#"warningreason"];
[device setValue:AuditStartDate forKey:#"starttimedate"];
[device setValue:userid forKey:#"userid"];
[device setValue:imageArray[i] forKey:#"auditimage"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"AuditPost" inManagedObjectContext:context];
[newDevice setValue:Audit forKey:#"auditnameId"];
[newDevice setValue:Passarray[i] forKey:#"checklistid"];
[newDevice setValue:CheckpointNameIDArray[i] forKey:#"checkpointid"];
[newDevice setValue:FailString forKey:#"failreason"];
[newDevice setValue:WarningString forKey:#"warningreason"];
[newDevice setValue:AuditStartDate forKey:#"starttimedate"];
[newDevice setValue:userid forKey:#"userid"];
[newDevice setValue:imageArray[i] forKey:#"auditimage"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
}
But it saves whole array in just a single string. I need to store array element one by one in Core Data as String.
How is it possible?
Can do in just simple steps.
AppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newData;
for (int i = 0; i < array1.count; i++){
newData = [NSEntityDescription insertNewObjectForEntityForName:#"yourEntityName" inManagedObjectContext:context];
[newData setValue:array1[i] forKey:#"sub-entities"];
[newData setValue:array2[i] forKey:#"sub-entities"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}else {
NSLog(#"Data saved successfully ..");
}
Saving multiple array array1 & array2 to the sub-entities of an entity.
You can convert it as follow
NSArray *arrayToBeConvertedInToString = #[#"This", #"is", #"an", #"array"];
NSString * result = [[arrayToBeConvertedInToString valueForKey:#"description"] componentsJoinedByString:#" "];
NSLog(#"Array in string: %#", result);
You can use method explained by Richard G
I ll suggest you to convert it into NSData and store it as transferable in coreData
Converting into NSData
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arrayName];
Storing into CoreData
[newManagedObject setValue:nsData forKey:#"auditid"];
Be sure you have changed datatype to transformable in coredata

How to update coredata value in Objective-C

I am new in iOS and I am facing a problem regarding to update value of coredata.
For Save
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *device;
if (self.device) {
// Update existing device
[device setValue:GlobalIndexPath forKey:#"key"];
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Device" inManagedObjectContext:context];
[newDevice setValue:GlobalIndexPath forKey:#"key"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
My code to fetch core data is
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"EntityName" inManagedObjectContext:context]];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
And to update I and using code
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:#"1" forKey:#"Key"];
Update code not update it add one object.
Note - GlobalIndexPath is a name of string.
But this is not working for me any suggestion. Thanks in Advcance!
You need to save the context every time you make changes to any NSManagedObject and want it to persist. Try this:
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:#"1" forKey:#"Key"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}

iOS sqlite storing null value without calling setValue

I am trying to store product in sqlite. When i setValue for database entity then i store correct value.
But problem is that i make a check if product is already in database then it should not add same product again. But next time it store NULL value in database.
Although i am not calling [addToFav setValue:#"My Value"];
Simply its check in for loop. When my loop runs it won't go in first condition where i make counter if(count == 0)
I don't know where from its storing NULL value. While i am not calling it any where else. So how its storing NULL value in database ?
- (IBAction)buttonAddToFavourite:(id)sender {
int count = 0;
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error=nil;
NSManagedObject *addToFav = [NSEntityDescription insertNewObjectForEntityForName:#"Favourite" inManagedObjectContext:context];
NSString *dish = [results objectForKey:#"id"];
fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Favourite" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSString *id1 = [info valueForKey:#"dishid"];
if ([id1 isEqualToString:dish]) {
count = count +1;
}
}
if (count == 0) {
[addToFav setValue:[results objectForKey:#"id"] forKey:#"dishid"];
[CSNotificationView showInViewController:self
tintColor:[UIColor greenColor]
image:[UIImage imageNamed:#"sucess"]
message:#"Saved As Favourite."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
else if (count > 0){
[CSNotificationView showInViewController:self
tintColor:[UIColor redColor]
image:[UIImage imageNamed:#"warning"]
message:#"Dish Already Added."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
- (IBAction)buttonAddToFavourite:(id)sender {
NSError *error = nil;
NSString *dishId = results[#"id"];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Favourite"];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"dishid == %#", dishId]];
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects.count) {
[CSNotificationView showInViewController:self
tintColor:[UIColor redColor]
image:[UIImage imageNamed:#"warning"]
message:#"Dish Already Added."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
else {
Favourite *obj = [NSEntityDescription insertNewObjectForEntityForName:#"Favourite" inManagedObjectContext:self.managedObjectContext];
obj.dishid = dishId;
[CSNotificationView showInViewController:self
tintColor:[UIColor greenColor]
image:[UIImage imageNamed:#"sucess"]
message:#"Saved As Favourite."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
}

fetch request returning null after code removed that inserts data

In the code below (in ViewDidLoad), I import a JSON file into an iOS project, and then persist the data using Core Data and, at the end, perform a fetch request successfully. However, after I remove the code that imports the file and persists the data, the fetch request starts returning (null). Based on the code below, can you explain why this is happening?
id delegate = [[UIApplication sharedApplication] delegate];
self.managedObjectContext = [delegate managedObjectContext];
NSError* err = nil;
NSString* dataPath = [[NSBundle mainBundle] pathForResource:#"inventorydata" ofType:#"json"];
NSArray* inventoryData = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
if(err) NSLog(#"Error %#",[err description]);
NSLog(#"Imported Data: %#", inventoryData);
[Questions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Inventory *partsInfo= [NSEntityDescription
insertNewObjectForEntityForName:#"Inventory"
inManagedObjectContext:self.managedObjectContext];
partsInfo.name = [obj objectForKey:#"name"];
partsInfo.sku = [obj objectForKey:#"sku"];
Supplier *supplierInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"Supplier"
inManagedObjectContext:self.managedObjectContext];
supplierInfo.supplierId = [obj objectForKey:#"supplierId"];
[supplierInfo setValue:[NSSet setWithObject:partsInfo ] forKey:#"partData"];
}];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Supplier"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
self.fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (Supplier *info in self.fetchedObjects) {
NSLog(#"supplierId: %#", info.supplierId);
}
Try this.
[Questions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Inventory *partsInfo= [NSEntityDescription
insertNewObjectForEntityForName:#"Inventory"
inManagedObjectContext:self.managedObjectContext];
partsInfo.name = [obj objectForKey:#"name"];
partsInfo.sku = [obj objectForKey:#"sku"];
Supplier *supplierInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"Supplier"
inManagedObjectContext:self.managedObjectContext];
supplierInfo.supplierId = [obj objectForKey:#"supplierId"];
[supplierInfo setValue:[NSSet setWithObject:partsInfo ] forKey:#"partData"];
}];
//Add this code : need to save database.
[delegate saveContext];
// You should add this method in AppDelegate.m
- (void)saveContext{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}

Resources