Getting Null Value From Database NSManagedObject - ios

I am developing iOS app, which fetch data from Web Services and save it to local database and uses it various views as needed. The data is fetch from Web Service and save to database correctly. But while accessing data from NSManagedObject it show FAULT and the consequent NSDictionary shows null Values
The code follows:-
-(void)SaveData:(NSInteger)menuId categoryID:(NSInteger)catID caption:(NSString *)title parentID:(NSInteger)parentID
{
BBAppDelegate *appDelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *userobj = [NSEntityDescription insertNewObjectForEntityForName:tableName
inManagedObjectContext:context];
[userobj setValue:[NSNumber numberWithInt:menuId] forKey:#"id"];
[userobj setValue:[NSNumber numberWithInt:catID] forKey:#"catid"];
[userobj setValue:[NSNumber numberWithInt:parentID] forKey:#"parentid"];
[userobj setValue:title forKey:#"caption"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
NSLog(#"app dir: %#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
}
-(NSArray *)fetchedData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *readData = [[NSFetchRequest alloc] init];
[readData setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription
entityForName:tableName inManagedObjectContext:context];
[readData setEntity:entity];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:readData error:&error];
// for (Test *test in array)
// {
// NSLog(#"Test: %# ", test.text);
// }
NSLog(#"%#",results);
return results;
}
-(void)removeData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *delData = [[NSFetchRequest alloc]init];
[delData setEntity:[NSEntityDescription entityForName:tableName inManagedObjectContext:context]];
[delData setIncludesPropertyValues:NO];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:delData error:&error];
for (NSManagedObject *value in result) {
[context deleteObject:value];
}
NSError *saveError = nil;
[context save:&saveError];
}
-(void)table:(NSString *)nameTable{
tableName =nameTable;
}
- (instancetype)initWithTableName:(NSString *)tablename
{
[self table:tablename];
return self;
}
-(NSMutableArray *)buldMenu{
NSArray *array = [self fetchedData];
return [self getmenus:0 arr:array];
}
-(NSMutableArray *)getmenus:(NSInteger)parentID arr: (NSArray *)array
{
NSMutableArray *aray = [[NSMutableArray alloc]init];
for (NSManagedObject *dic in array) {
if (dic.faultingState != 0) {
NSLog(#"%lu",(unsigned long)dic.faultingState);
//return nil;
}
NSArray *keys = [[[dic entity] attributesByName] allKeys];
NSLog(#"%#",keys);
NSDictionary *dict = [dic dictionaryWithValuesForKeys:keys];
NSLog(#"%#",dic);
NSLog(#"%#",dict);
NSInteger pID = [[dict objectForKey:#"parentid"]integerValue];
if (pID == parentID) {
BBMenuEntry *entryMenu = [[BBMenuEntry alloc]init];
entryMenu.menuID = [[dict objectForKey:#"id"]integerValue];
entryMenu.catID = [[dict objectForKey:#"catid"]integerValue];
entryMenu.caption = [dict objectForKey:#"caption"];
entryMenu.subMenus = [self getmenus:entryMenu.menuID arr:array];
[aray addObject:entryMenu];
}
}
return aray;
}

Related

How to delete entries in core data

i am new to core data..
I know how to store and item.
- (void)dbSave:(NSString *)uri withContent:(NSDictionary *)content withExpiry:(double)date {
Cache *cache = [self dbLoad:uri];
if (cache == nil) {
cache = [NSEntityDescription insertNewObjectForEntityForName:#"Cache" inManagedObjectContext:[self managedObjectContext]];
}
double time = (double) [[NSDate date] timeIntervalSince1970] + date;
[cache setLocal:uri];
[cache setTime:#(time)];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:content forKey:#"data"];
[archiver finishEncoding];
[cache setData:data];
NSError *error;
if (![[self managedObjectContext] save:&error]) {
}
}
But i am stuck with creating a method to clear this core data data base.. Does anyone know how?
NSManagedObjectContext *managedObjectContext=[appDelegate managedObjectContext];
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:#"entity"];
NSArray* currentRecord = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
if (currentRecord.count)
{
for (NSManagedObject *obj in currentRecord)
{
[managedObjectContext deleteObject:obj];
}
NSError * error = nil;
if (![managedObjectContext save:&error])
NSLog(#"Can't save ! %# %#",error,[error localizedDescription]);
else
NSLog(#"Data deleted");
}
use this
NSManagedObjectContext *managedContext = [[APP_DELEGATE dbManagerObj] newPrivateContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Cache"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isUserData = %#",[NSNumber numberWithBool:true]];
[fetchRequest setPredicate:predicate];
if (IS_IOS9_ANDABOVE) {
NSBatchDeleteRequest *batchDeleteRequest = [[NSBatchDeleteRequest alloc]initWithFetchRequest:fetchRequest];
[[[APP_DELEGATE dbManagerObj]persistentStoreCoordinator]executeRequest:batchDeleteRequest withContext:managedContext error:nil];
}
else
{
NSArray *userRelatedDay = [managedContext executeFetchRequest:fetchRequest error:nil];
for (NSManagedObject *object in userRelatedDay) {
[managedContext deleteObject:object];
}
}

Store NSDictionary In CoreData ios not working

Since I get into a requirement of saving NSDictionary offline and populate the table from it when the user is offline.
This is the code I have so far:
Everytime the resulting NSDictionary was getting as nil
I have made this attribute set as transformable
+ (void) insertIntoCoredata :(NSString *) table : (NSString *) attribute : (NSArray *) dic {
AppDelegate *appDelegate =(AppDelegate*)
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
appDelegate.managedObjectContext;
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:dic];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:table
inManagedObjectContext:context];
[object setValue:myData forKey:attribute];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
}
+ (id) getFromCoredata :(NSString *) table : (NSString *) attribute {
AppDelegate *appDelegate =(AppDelegate*)
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
appDelegate.managedObjectContext;
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:table
inManagedObjectContext:context];
[fetch setEntity:entityDescription];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetch error:&error];
if([fetchedObjects count] == 1)
return [fetchedObjects objectAtIndex:0];
else
return nil;
}
What went wrong with this code.

I cannot insert value with NSNumber datatype into my coredata

Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'Unacceptable type of value for
attribute: property = "XXXXX"; desired type = NSNumber; given type =
NSTaggedPointerString; value = 0.'
Tried: [enter image description here][1]
[message setValue:localID forKey:#"local_id"];
localID is of type NSNumber
DataModel image: [1]: https://i.stack.imgur.com/7WTlU.png
[self insertInLocatDB:print_data entityName:#"Message_data" withPredicate:#"receiver_id" filterWith:#"unique_id"];
Using this to insert into CoreData:
-(void)insertInLocatDB :(NSMutableArray *)arr_msg entityName:(NSString*)name withPredicate:(NSString*)predicateText filterWith:(NSString*)filterText
{
NSEntityDescription *entitydesc=[NSEntityDescription entityForName:name inManagedObjectContext:app.context];
NSFetchRequest *request=[[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSInteger local_id =[self getMaxLocalId:name];
for(int i=0; i<[arr_msg count]; i++)
{
[fetched_data removeAllObjects];
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"%# like %# ",predicateText,[[arr_msg objectAtIndex:i]objectForKey:predicateText]];
[request setPredicate:predicate];
NSError *error;
NSArray *matchingData=[app.context executeFetchRequest:request error:&error];
local_id=local_id+1;
for (NSManagedObject *obj in matchingData)
{
[fetched_data addObject:[obj valueForKey:filterText]];
}
NSString *filter=[[arr_msg objectAtIndex:i] objectForKey:filterText];
if(![fetched_data containsObject:filter])
{
NSManagedObject *message=[[NSManagedObject alloc] initWithEntity:entitydesc insertIntoManagedObjectContext:app.context];
[arr_keys setArray:[[arr_msg objectAtIndex:i] allKeys]];
[arr_values setArray:[[arr_msg objectAtIndex:i] allValues]];
[message setValue:[NSNumber numberWithInteger:local_id] forKey:#"local_id"];
for (int i=0;i<[arr_keys count];i++)
{
if( [[message.entity propertiesByName] objectForKey:[arr_keys objectAtIndex:i]] != nil
&& ([[[message.entity propertiesByName] objectForKey:[arr_keys objectAtIndex:i]] isKindOfClass:[NSAttributeDescription class]]) )
{
[message setValue:[arr_values objectAtIndex:i] forKey:[arr_keys objectAtIndex:i]];
}
}
[arr_keys removeAllObjects];
[arr_values removeAllObjects];
}
}
}
If you have a core data attribute as shown in my screen shot.
Then, the following snippet of code will work for you.
BOOL result;
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *newMessage = [NSEntityDescription insertNewObjectForEntityForName:#"message"
inManagedObjectContext:context];
[newMessage setValue:[NSNumber numberWithInt:local_id] forKey:#"local_id"];
[newMovie setValue:movieName forKey:#"message"];
NSError *error = nil;
// Save the object to persistent store
result = YES;
if (![context save:&error]) {
result = NO;
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
return result;
and a function to get the managed object context
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
Edited Code of Sandhya.
-(NSInteger)getMaxLocalId :(NSString*)entitiyName
{
NSEntityDescription *entitydesc=[NSEntityDescription entityForName:entitiyName inManagedObjectContext:app.context];
NSFetchRequest *request=[[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSInteger local_id = 0;
request.fetchLimit = 1;
request.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"local_id" ascending:NO]];
NSError *error = nil;
local_id=[[app.context executeFetchRequest:request error:&error].firstObject integerValue];
return local_id;
}
Then used the following to insert in to CoreData
NSInteger local_id =[self getMaxLocalId:name];
local_id=local_id+1;
[message setValue:[NSNumber numberWithInteger:local_id] forKey:#"local_id"];
make sure you get the local_id.
As you have NSInteger, For conversion you should use [NSNumber numberWithInteger:] Instead of [NSNumber numberWithInt:]
UPDATE 2 :
NSString *filter=[[arr_msg objectAtIndex:i] objectForKey:filterText];
if(![fetched_data containsObject:filter])
{
NSManagedObject *message=[[NSManagedObject alloc] initWithEntity:entitydesc insertIntoManagedObjectContext:app.context];
[arr_keys setArray:[[arr_msg objectAtIndex:i] allKeys]];
[arr_values setArray:[[arr_msg objectAtIndex:i] allValues]];
[message setValue:[NSNumber numberWithInteger:local_id] forKey:#"local_id"];
for (int i=0;i<[arr_keys count];i++)
{
if( [[message.entity propertiesByName] objectForKey:[arr_keys objectAtIndex:i]] != nil
&& ([[[message.entity propertiesByName] objectForKey:[arr_keys objectAtIndex:i]] isKindOfClass:[NSAttributeDescription class]]) )
{
if(![[arr_keys objectAtIndex:i] isEqualToString:#"local_id"]){
[message setValue:[arr_values objectAtIndex:i] forKey:[arr_keys objectAtIndex:i]];
}
}
}
[arr_keys removeAllObjects];
[arr_values removeAllObjects];
}
-(NSInteger)getMaxLocalId :(NSString*)entitiyName
{
NSEntityDescription *entitydesc=[NSEntityDescription entityForName:entitiyName inManagedObjectContext:app.context];
NSFetchRequest *request=[[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSInteger local_id = 0;
request.fetchLimit = 1;
request.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"local_id" ascending:NO]];
NSError *error = nil;
local_id=[[app.context executeFetchRequest:request error:&error].firstObject integerValue];
return local_id;
}
Then used the following to insert in to CoreData
NSInteger local_id =[self getMaxLocalId:name];
local_id=local_id+1;
[message setValue:myNumber forKey:#"local_id"];

general model implementation by Core Data and NSFetchedResultsController

I am newbie in Core Data. I put all model requirements (in respect of MVC) in a class of NSFetchedResultsController as below:
Header File :
#import <CoreData/CoreData.h>
#interface GeneralModel : NSFetchedResultsController
#property (nonatomic, strong) NSManagedObjectContext *context;
#property (nonatomic, strong) NSManagedObjectModel *model;
- (NSString *)storagePath;
- (void)removeStorage;
- (void)truncateAllEntity;
- (void)truncateEntity:(NSString *)entityName;
- (void)addGroups:(NSDictionary *)insertData;
- (NSArray *)getEntity:(NSString *)entityName sortBy:(NSString *)sortAttribute;
- (id)getMaxValue:(NSString *)entityName forProperty:(NSString *)propertyName;
- (NSArray *)getEntity:(NSString *)entityName predicateBy:(NSPredicate *)predicate sortBy:( NSString * )sortAttribute;
#end
Main File:
#import "GeneralModel.h"
#import "GeneralHelper.h"
#implementation GeneralModel
- (instancetype)init
{
self = [super init];
if (self) {
// Read in Model.xcdatamodeld
_model = [NSManagedObjectModel mergedModelFromBundles:nil];
NSPersistentStoreCoordinator *psc =
[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_model];
// Where does the SQLite file go?
NSString *path = self.storagePath;
NSURL *storeURL = [NSURL fileURLWithPath:path];
NSError *error = nil;
if (![psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:&error]) {
#throw [NSException exceptionWithName:#"OpenFailure"
reason:[error localizedDescription]
userInfo:nil];
}
// Create the managed object context
_context = [[NSManagedObjectContext alloc] init];
_context.persistentStoreCoordinator = psc;
}
return self;
}
- (NSString *)storagePath
{
NSArray *documentDirectories =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
// Get one and only document directory from that list
NSString *documentDirectory = [documentDirectories firstObject];
return [documentDirectory stringByAppendingPathComponent:#"model.sqlite"];
}
- (void)removeStorage {
// NSError *error2;
// NSString *storagePath = [self storagePath];
//
// NSDictionary *options = #{NSPersistentStoreUbiquitousContentNameKey: #"model"};
// bool removeResult = [NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:[NSURL URLWithString:storagePath] options:options error:&error2];
// if (removeResult == NO) {
// NSLog(#"Could not remove Storage. Reason: %#", error2.localizedFailureReason);
// }
NSPersistentStore *store = [self.context.persistentStoreCoordinator.persistentStores lastObject];
NSError *error = nil;
NSURL *storeURL = store.URL;
BOOL isRemovePersistentStore = [self.context.persistentStoreCoordinator removePersistentStore:store error:&error];
if (isRemovePersistentStore == NO) {
NSLog(#"NO RemovePersistentStore. Reason: %#", error.localizedFailureReason);
}
BOOL isRemoveItemAtURL = [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
if (isRemoveItemAtURL == NO) {
NSLog(#"NO RemoveItemAtURL. Reason: %#", error.localizedFailureReason);
}
}
- (void)truncateAllEntity {
NSArray *entities = self.model.entities;
for (NSEntityDescription *entityDescription in entities) {
[self truncateEntity:entityDescription.name];
}
}
- (void)truncateEntity:(NSString *)entityName {
// delete all database
if (IOS_VERSION >= 9) {
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:entityName];
NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];
NSError *deleteError = nil;
[self.context.persistentStoreCoordinator executeRequest:delete withContext:self.context error:&deleteError];
} else {
NSFetchRequest *allItems = [[NSFetchRequest alloc] init];
[allItems setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:self.context]];
[allItems setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *items = [self.context executeFetchRequest:allItems error:&error];
//error handling goes here
for (NSManagedObject *item in items) {
[self.context deleteObject:item];
}
NSError *saveError = nil;
[self.context save:&saveError];
//more error handling here
}
[self.context rollback];
}
- (void)addGroups:(NSDictionary *)insertData {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
for (NSDictionary *response in insertData) {
NSManagedObject *existingGroup = [self getEntity:#"Group" AtValue:response[#"groupId"] forProperty:#"group_id" ];
if (existingGroup) {
NSLog(#"existingGroup");
continue;
}
// for (int i; i<=20; i++) {
// set bullet
NSManagedObject *object_bullet = [NSEntityDescription insertNewObjectForEntityForName:#"Group_bullet"
inManagedObjectContext:self.context];
NSData *bulletData = [[NSData alloc] initWithBase64EncodedString:response[#"bullet"] options:NSDataBase64DecodingIgnoreUnknownCharacters];
[object_bullet setValue:bulletData forKey:#"bullet"];
[object_bullet setValue:response[#"groupId"] forKey:#"group_id"];
// set group
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Group"
inManagedObjectContext:self.context];
[object setValue:object_bullet forKey:#"relatedBullet"];
// NSDate *createDate = [dateFormatter dateFromString:response[#"createDate"]];
// [object setValue:createDate forKey:#"group_created_date"];
NSNumber *createDate = response[#"createDate"];
[object setValue:[NSDate dateWithTimeIntervalSince1970:[createDate doubleValue]] forKey:#"group_created_date"];
[object setValue:response[#"groupId"] forKey:#"group_id"];
[object setValue:[GeneralHelper getInteger:response[#"memberNumber"]] forKey:#"group_members_count"];
[object setValue:response[#"name"] forKey:#"group_name"];
[object setValue:[GeneralHelper getInteger:response[#"privacy"]] forKey:#"group_privacy"];
[object setValue:#1 forKey:#"group_status"];
[object setValue:response[#"imageName"] forKey:#"image_name"];
[object setValue:response[#"lastMessageId"] forKey:#"last_message_id"];
[object setValue:response[#"lastMessageText"] forKey:#"last_message_text"];
//
// NSDate *lastMessageDate = [dateFormatter dateFromString:response[#"lastMessageDate"]];
// [object setValue:lastMessageDate forKey:#"last_time"];
NSNumber *lastMessageDate = response[#"lastMessageDate"];
[object setValue:[NSDate dateWithTimeIntervalSince1970:[lastMessageDate doubleValue]] forKey:#"last_time"];
[object setValue:response[#"machineId"] forKey:#"machine_id"];
NSNumber *timestamp = response[#"timestamp"];
[object setValue:[NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]] forKey:#"timestamp"];
[object setValue:[GeneralHelper getInteger:response[#"unreadCount"]] forKey:#"unread_count"];
// }
}
NSError *errorInsert;
if (![self.context save:&errorInsert]) {
NSLog(#"Failed to save - error: %#", [errorInsert localizedDescription]);
}
[self.context rollback];
}
- (id)getMaxValue:(NSString *)entityName forProperty:(NSString *)propertyName {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:entityName];
fetchRequest.fetchLimit = 1;
fetchRequest.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:propertyName ascending:NO]];
NSError *error = nil;
id maxValue = [self.context executeFetchRequest:fetchRequest error:&error].firstObject;
if (maxValue == nil) {
maxValue = #{propertyName : #0};
}
[self.context rollback];
return [maxValue valueForKey:propertyName];
}
- (id)getEntity:(NSString *)entityName AtValue:(NSString *)indexValue forProperty:(NSString *)propertyName {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K == %#", propertyName, indexValue];
// NSLog(#"predicate: %#", predicate);
[request setEntity:entity];
[request setPredicate:predicate];
[request setFetchLimit:1];
NSError *error;
NSArray *results = [self.context executeFetchRequest:request error:&error];
NSManagedObject *object = [results firstObject];
// if (object) {
// // there is at least one object matching you predicate
// } else {
// // there is no object matching your predicate in the moc
// }
// NSLog(#"results member %#", results);
// [self.context rollback];
return object;
}
Then I use this general model in my UITableViewController.
Is there any better way to do this? Or my implementation is buggy and useless?
It think this is a nice approach, but it has some drawbacks.
An NSFetchedResultsController is responsible, as the name implies for controlling results that were fetched. If you add functionality like deleting and modifying things, you are making an object with too many responsibilities.
Imagine there is one viewController showing results in a tableview. It would only need the fetchedresultscontroller functionality, nothing more. If by tapping on a cell you go into a new view controller where edits are possible, you don't need a fetchedresultscontroller: you need a managedObject to edit. This editViewController could use a child context of the tableViewController so that on cancel, all edits are discarded by simply discarding the child context.
I would suggest to no subclass the NSFetchedResultsController, but instead implement a subclass of NSObject that you initialize with an NSNMagedObjectContext that can do the things that apply to the entire context. Like adding groups, removing all data etc.
Then use composition: this NSObject subclass can be a property of a viewController so the viewCOntroller has a way to do those things without having this operation being specific to this viewController.
In general, instead of subclassing, consider composition first. This is because transforming a small components of a composed object to an object that is a certain subclass is usually easier then the other way around.
Feel free to disagree :), but this is what I've learned from experience of working with many people for a long time on a very large codebase.

fetch core data and save it to nsarray

i think this is not tought but i'm facing problem with these.
i am fecthing core date and after fetching it i'm trying to save it into nsarray.
but every time last data from database is saving into array. i want every data inserted into databases.
suppose i have an attribute name account_name
i added A,B,C,X,Y,Z. in this code i'm just getting last value Z in my array. :(
but when i print it then i'm getting all data..
any solution ?
NSArray *fetchedObjects;
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Chart_of_Accounting" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *obj in fetchedObjects) {
debitArray = [NSMutableArray arrayWithObject:[obj valueForKey:#"account_name"]];
creditArray = [NSMutableArray arrayWithObject:[obj valueForKey:#"account_name"]];
NSLog(#"Account Name: %#", [obj valueForKey:#"account_name"]);
}
Try this
NSArray *fetchedObjects;
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Chart_of_Accounting" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSMutableArray *debitArray = [[NSMutableArray alloc] init];
NSMutableArray *creditArray = [[NSMutableArray alloc] init];
for (NSManagedObject *obj in fetchedObjects) {
[debitArray addObject:[obj valueForKey:#"account_name"]];
[creditArray addObject:[obj valueForKey:#"account_name"]];
NSLog(#"Account Name: %#", [obj valueForKey:#"account_name"]);
}
Because, every time its get initialised . Use addObject
debitArray = creditArray = [[NSMutableArray alloc] init];
for (NSManagedObject *obj in fetchedObjects) {
[debitArray addObject:[obj valueForKey:#"account_name"]];
[creditArray addObject:[obj valueForKey:#"account_name"]];
}NSLog(#"Account Name: %#", [obj valueForKey:#"account_name"]);
In your loop:
for (NSManagedObject *obj in fetchedObjects) {
debitArray = [NSMutableArray arrayWithObject:[obj valueForKey:#"account_name"]];
creditArray = [NSMutableArray arrayWithObject:[obj valueForKey:#"account_name"]];
NSLog(#"Account Name: %#", [obj valueForKey:#"account_name"]);
}
you are instantiating a new array each time (and overriding the previous one). That explains what is happening.
You should instantiate the array outside of the loop, then add your objects to it within the loop.
debitArray = [NSMutableArray arrayWithCapacity:[fetchedObjects count]];
creditArray = [NSMutableArray arrayWithCapacity:[fetchedObjects count]];
for (NSManagedObject *obj in fetchedObjects) {
[debitArray addObject:[obj valueForKey:#"account_name"]];
[creditArray addObject:[obj valueForKey:#"account_name"]];
NSLog(#"Account Name: %#", [obj valueForKey:#"account_name"]);
}
Don't create duplicate values in different array.
return your fetchedObjects data as NSArray Type then retrive from coredata.
fetchedObjects=[self yourRetriveMethod];
for (NSManagedObject *obj in fetchedObjects) {
debitArray = [NSMutableArray arrayWithObject:[obj valueForKey:#"account_name"]];
creditArray = [NSMutableArray arrayWithObject:[obj valueForKey:#"account_name"]];
NSLog(#"Account Name: %#", [obj valueForKey:#"account_name"]);
}

Resources