In Core data unable to store objects - ios

My code here i am trying to add list of object in to my array form that array i trying to add it to code data attributes.
#import "ViewController.h"
#import "model.h"
#import "coredataManager.h"
#interface ViewController ()
{
NSMutableArray *entries;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
entries = [[NSMutableArray alloc]init];
coredataManager *coreobj = [[coredataManager alloc]init];
model *obj = [[model alloc]initWithContents:#"1" alternateLink:#"1" DownloadURL:#"1"];
model *obj2 = [[model alloc]initWithContents:#"2" alternateLink:#"2" DownloadURL:#"2"];
model *obj3 = [[model alloc]initWithContents:#"3" alternateLink:#"3" DownloadURL:#"3"];
[entries addObject:obj];
[entries addObject:obj2];
[entries addObject:obj3];
NSLog(#"%#",entries);
[coreobj StoreValues:entries];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
my NSObject Class
#import <Foundation/Foundation.h>
#interface model : NSObject
#property(copy)NSString *filename;
#property(copy)NSString *alternatelink;
#property(copy)NSString *downloadurl;
-(id)initWithContents:(NSString *)Fname alternateLink :(NSString *) ALink DownloadURL :(NSString *)DURL;
#end
NSObject Implementation File
#import "model.h"
#implementation model
#synthesize downloadurl,filename,alternatelink;
-(id)initWithContents:(NSString *)Fname alternateLink :(NSString *) ALink DownloadURL :(NSString *)DURL
{
if ((self = [super init])) {
downloadurl = [DURL copy];
filename = [Fname copy];
alternatelink = [ALink copy];
}
return self;
}
#end
Code to store in core data
-(void)StoreValues:(NSMutableArray *) sample
{
Sample *value = [NSEntityDescription insertNewObjectForEntityForName:#"Sample"
inManagedObjectContext:self.managedObjectContext];
for (int i=0;i<sample.count;i++)
{
model *obj=[sample objectAtIndex:i];
value.url = obj.downloadurl;
value.filename = obj.filename;
value.alternate = obj.alternatelink;
}
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
But only the last value of the array is getting stored in the core data can any one guide me solve this issue
Thanks in advance.

Before you save, you rewrite the object. Do this instead:
Sample *value;
for (int i=0;i<sample.count;i++)
{
value = [NSEntityDescription insertNewObjectForEntityForName:#"Sample"
inManagedObjectContext:self.managedObjectContext];
model *obj=[sample objectAtIndex:i];
value.url = obj.downloadurl;
value.filename = obj.filename;
value.alternate = obj.alternatelink;
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
That saves the object after every iteration and doesn't rewrite it. Then starts anew.

Related

Healthkit: Data not showing first time running.

I have a strange problem when reading data out of healthkit. The first time when i press the button the weight is printed 0, the next times i press the button the weight is printed as normal.I would really appreciate it if someone could help me.
Thanks!
I have the following code.
HealtkitManager.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <HealthKit/HealthKit.h>
#interface HealthKitManager : NSObject
#property (nonatomic) float weight;
#property (nonatomic) HKHealthStore *healthStore;
+(HealthKitManager *)sharedManager;
-(void) requestAuthorization;
-(double) readWeight;
#end
Healthkitmanager.m
#import "HealthKitManager.h"
#import <healthKit/healthKit.h>
#import "StartScreen.h"
#interface HealthKitManager ()
#end
#implementation HealthKitManager
+(HealthKitManager *) sharedManager{
static dispatch_once_t pred = 0;
static HealthKitManager *instance = nil;
dispatch_once(&pred, ^{
instance = [[HealthKitManager alloc]init];
instance.healthStore = [[HKHealthStore alloc]init];
});
return instance;
}
-(void)requestAuthorization {
if([HKHealthStore isHealthDataAvailable]==NO){
return;
}
NSArray *readTypes = #[[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyFatPercentage]];
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:[NSSet setWithArray:readTypes] completion:nil];
}
-(double) readWeight{
NSMassFormatter *massFormatter = [[NSMassFormatter alloc]init];
massFormatter.unitStyle = NSFormattingUnitStyleLong;
HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
[self fetchMostRecentDataOfQuantityType:weightType withCompletion:^(HKQuantity *mostRecentQuantity, NSError *error) {
if(!mostRecentQuantity){
NSLog(#"%#",#"Error. ");
}
else{
HKUnit *weightUnit = [HKUnit gramUnit];
_weight = [mostRecentQuantity doubleValueForUnit:weightUnit];
_weight = (float)_weight/1000.00f;
}
}];
return _weight;
}
- (void)fetchMostRecentDataOfQuantityType:(HKQuantityType *)quantityType withCompletion:(void (^)(HKQuantity *mostRecentQuantity, NSError *error))completion {
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType predicate:nil limit:1 sortDescriptors:#[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
if (!results) {
if (completion) {
completion(nil, error);
}
return;
}
if (completion) {
HKQuantitySample *quantitySample = results.firstObject;
HKQuantity *quantity = quantitySample.quantity;
completion(quantity, error);
}
}];
[self.healthStore executeQuery:query];
}
#end
Startscreen.m
#import "StartScreen.h"
#import "HealthKitManager.h"
#interface StartScreen ()
#property(nonatomic,weak) IBOutlet UILabel *weightLabel;
#end
#implementation StartScreen
- (void)viewDidLoad {
[super viewDidLoad];
[[HealthKitManager sharedManager] requestAuthorization];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)readAgeButtonPressed:(id)sender{
HealthKitManager *readWeight = [[HealthKitManager sharedManager] init];
NSLog(#"%.2f",readWeight.readWeight);
}
#end
You use singleton HealthKitManager but your code
HealthKitManager *readWeight = [[HealthKitManager sharedManager] init];
in IBAction readAgeButtonPressed should be
HealthKitManager *readWeight = [HealthKitManager sharedManager];
You don't need init.
Also, you can change the code
[[HealthKitManager sharedManager] requestAuthorization];
to be
HealthKitManager *readWeight = [HealthKitManager sharedManager];
[readWeight requestAuthorization];
NSLog(#"%.2f",readWeight.readWeight);
checking the value of readWeight.

NSSet property returning count of 1 when added to CoreData via Mantle

so I have an object with several properties that I want to add to coredata however I'm using the Mantle framework that I am not too familiar with.
My Object(.h):
#import <Foundation/Foundation.h>
#import "RTModel.h"
#import CoreLocation;
#class RTPhoto;
#class RTContact;
#class RTUser;
#interface MyInteraction : RTModel <NSCopying, MTLJSONSerializing>
+ (NSManagedObject *)managedObjectWithIdentifier:(NSNumber *)identifier;
- (NSManagedObject *)managedObject;
#property (nonatomic, strong) NSNumber *latitude;
#property (nonatomic, strong) NSNumber *longitude;
#property (strong, nonatomic) RTUser *user;
#property (nonatomic, strong) NSNumber *createdByID;
#property (nonatomic, copy) NSString *createdByLabel;
#property (nonatomic, copy) NSString *interactedWithLabel;
#property (strong, nonatomic) NSString *publicShareURLString;
#property (nonatomic, strong) NSSet *photos;
- (void)addPhotosObject:(RTPhoto *)photo;
#end
My Object(.m):
#import "OUTInteraction.h"
#import "RTComment.h"
#import "RTPhoto.h"
#import "RTUser.h"
#import "RTContact.h"
#import "OUTCoreDataController.h"
#import "OUTInteractionsController.h"
#interface MyInteraction () <UIActionSheetDelegate>
#end
#implementation MyInteraction
#synthesize identifier = _identifier;
#synthesize createdAt = _createdAt;
#synthesize updatedAt = _updatedAt;
- (void)deleteWithCompletion:(void (^)(NSError *))completion
{
NSManagedObject *managedObject = [self managedObject];
if (!managedObject) {
completion(nil);
};
[[[MyCoreDataController sharedController] persistenceController] deleteObject:managedObject
saveContextAndWait:YES
completion:^(NSError *error) {
completion(error);
}];
}
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return [[super JSONKeyPathsByPropertyKey] mtl_dictionaryByAddingEntriesFromDictionary: #{
#"createdByID" : #"created_by_id",
#"createdByLabel" : #"created_by_label",
#"interactedWithLabel" : #"interacted_with_label",
#"interactionType" : #"interaction_type",
#"latitude" : #"latitude",
#"longitude" : #"longitude",
#"formID" : #"form_id",
#"formEntries" : #"form_entries",
#"interactedWithCity" : #"interacted_with_city",
#"interactedWithRegion" : #"interacted_with_region",
#"publicShareURLString" : #"share_url",
#"photos" : #"images"
}];
}
#pragma mark - Photos
- (void)addPhotosObject:(RTPhoto *)photo
{
if (!photo) return;
NSMutableSet *mutablePhotos = [NSMutableSet setWithSet:self.photos];
[mutablePhotos addObject:photo];
self.photos = [mutablePhotos copy];
}
- (BOOL)hasPhotoToDisplay
{
if (!self.photos) return NO;
if ([[self.photos allObjects] count] > 0) return YES;
return NO;
}
#pragma mark - JSON Transformers
/// #note used by Mantle
+ (NSValueTransformer *)photosJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSArray *array) {
NSMutableSet *mutableSet = [NSMutableSet set];
[array enumerateObjectsUsingBlock:^(NSDictionary *JSON, NSUInteger idx, BOOL *stop) {
NSError *error = nil;
RTPhoto *item = [MTLJSONAdapter modelOfClass:[RTPhoto class]
fromJSONDictionary:JSON
error:&error];
if (error) DDLogError([error description], nil);
[mutableSet addObject:item];
}];
NSLog(#"mutable set");
return mutableSet;
} reverseBlock:^id(NSSet *set) {
NSLog(#"all objects");
return [set allObjects];
}];
}
/// #note used by Mantle
+ (NSValueTransformer *)commentsJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSArray *array) {
NSMutableSet *mutableSet = [NSMutableSet set];
[array enumerateObjectsUsingBlock:^(NSDictionary *JSON, NSUInteger idx, BOOL *stop) {
NSError *error = nil;
RTComment *item = [MTLJSONAdapter modelOfClass:[RTComment class]
fromJSONDictionary:JSON
error:&error];
if (error) DDLogError([error description], nil);
[mutableSet addObject:item];
}];
return mutableSet;
} reverseBlock:^id(NSSet *set) {
return [set allObjects];
}];
}
/// #note used by Mantle
+ (NSValueTransformer *)contactsJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSArray *array) {
NSMutableSet *mutableSet = [NSMutableSet set];
[array enumerateObjectsUsingBlock:^(NSDictionary *JSON, NSUInteger idx, BOOL *stop) {
NSError *error = nil;
RTComment *item = [MTLJSONAdapter modelOfClass:[RTContact class]
fromJSONDictionary:JSON
error:&error];
if (error) DDLogError([error description], nil);
[mutableSet addObject:item];
}];
return mutableSet;
} reverseBlock:^id(NSSet *set) {
return [set allObjects];
}];
}
/// #note used by Mantle
+ (NSValueTransformer *)formEntriesJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSArray *entryDictionaries) {
NSMutableSet *set = [NSMutableSet set];
[entryDictionaries enumerateObjectsUsingBlock:^(NSDictionary *entryDict, NSUInteger idx, BOOL *stop) {
NSError *error = nil;
RTInteractionFormEntry *entry = [MTLJSONAdapter modelOfClass:[RTInteractionFormEntry class]
fromJSONDictionary:entryDict
error:&error];
[set addObject:entry];
}];
return set;
} reverseBlock:^id(NSSet *set) {
NSMutableArray *array = [NSMutableArray array];
[set enumerateObjectsUsingBlock:^(RTInteractionFormEntry *entry, BOOL *stop) {
[array addObject:[entry jsonDictionary]];
}];
return array;
}];
}
/// #note used by Mantle
+ (NSValueTransformer *)userJSONTransformer
{
return [MTLValueTransformer mtl_JSONDictionaryTransformerWithModelClass:[RTUser class]];
}
/// #note used by Mantle
+ (NSValueTransformer *)interactionTypeJSONTransformer
{
return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:#{
#"email" : #(kRTInteractionTypeEmail),
#"check_in" : #(kRTInteractionTypeCheckIn),
#"note" : #(kRTInteractionTypeNote),
#"meeting" : #(kRTInteractionTypeMeeting)
}];
}
#pragma mark - Core Data
+ (NSString *)managedObjectEntityName
{
return #"Interaction";
}
+ (NSSet *)propertyKeysForManagedObjectUniquing
{
return [NSSet setWithArray:#[#"identifier"]];
}
+ (NSDictionary *)managedObjectKeysByPropertyKey
{
return [[super managedObjectKeysByPropertyKey] mtl_dictionaryByAddingEntriesFromDictionary:#{
#"metadata" : [NSNull null],
#"identifier" : #"interactionIdentifier",
}];
}
+ (NSDictionary *)relationshipModelClassesByPropertyKey
{
return [[super relationshipModelClassesByPropertyKey] mtl_dictionaryByAddingEntriesFromDictionary:#{
#"comments" : [RTComment class],
#"formEntries" : [RTInteractionFormEntry class],
#"photos" : [RTPhoto class],
#"contacts" : [RTContact class],
#"user" : [RTUser class]
}];
}
#pragma mark - Actions
- (void)delete
{
[[MyInteractionsController controller] deleteInteraction:self
success:^{
} failure:^(NSError *error) {
DDLogError([error description], nil);
}];
}
+ (NSManagedObject *)managedObjectWithIdentifier:(NSNumber *)identifier
{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[MyInteraction managedObjectEntityName]];
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"interactionIdentifier == %#", identifier];
fetchRequest.fetchLimit = 1;
NSManagedObjectContext *managedObjectContext = [[MyCoreDataController sharedController] managedObjectContext];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest
error:&error];
NSLog(#"Results: %#", results);
if (error) {
DDLogError(#"Error fetching managed object: %#", [error description]);
}
return [results firstObject];
}
- (NSManagedObject *)managedObject
{
return [MyInteraction managedObjectWithIdentifier:self.identifier];
}
- (void)mergeValuesForKeysFromManagedObject:(NSManagedObject *)managedObject
{
if ([managedObject valueForKey:#"photos"]) {
NSMutableSet *combinedPhotos = [NSMutableSet setWithSet:self.photos];
for (NSManagedObject *photoManagedObject in [managedObject valueForKey:#"photos"]) {
RTPhoto *photo = [MTLManagedObjectAdapter modelOfClass:[RTPhoto class]
fromManagedObject:photoManagedObject
error:nil];
if (photo.identifier || photo.localImageData || photo.imageDataPendingUpload) {
[combinedPhotos addObject:photo];
}
}
self.photos = [combinedPhotos copy];
}
}
#end
Basically the problem I'm having when adding the whole object to CoreData
via Mantle is that everything gets added except when it reaches the photos property which is a NSSet it only adds one of the objects, usually the last one.
Here is when the object is added to the context using Mantle(in another file):
[MTLManagedObjectAdapter managedObjectFromModel:interaction
insertingIntoContext:self.context
error:&coreDataError];
If someone has any clue as to why there is only one photos object being added under the "photos" key. I'm unfamiliar with how mantle handles toMany relationships and how to get all of the children added. Thanks

How to store the json values once up to life time of app removing from mobile?

MY CODE
.h
#interface fileHandler : NSObject
#property NSMutableArray *arrCategoryList;
#property NSMutableDictionary *dicCategoryList;
#property NSMutableDictionary *dicAllSubCategoryList;
#property NSMutableDictionary *dicProductList;
+(fileHandler *)getDataHandler;
-(void)categoryStorage:(NSMutableArray *)arrCategory :(NSMutableDictionary *)dicCategory :(NSMutableDictionary *)dicSubCategory;
.m
static fileHandler *internalInstance=Nil;
static dispatch_once_t internalOnceToken=0;
#implementation fileHandler
-(id)init
{
self=[super init];
[self allocateMemory];
return self;
}
+(fileHandler *)getDataHandler
{
dispatch_once(&internalOnceToken,^{
internalInstance = [[fileHandler alloc] init];
if(internalInstance) {
NSLog(#"Internal instance created: %#", internalInstance);
}
});
if(internalOnceToken == -1) {
NSLog(#"Internal instance exists: %#", internalInstance);
}
return internalInstance;
}
-(void)allocateMemory
{ NSLog(#"incoming");
self.arrCategoryList=[[NSMutableArray alloc]init];
self.dicCategoryList=[[NSMutableDictionary alloc]init];
self.dicAllSubCategoryList=[[NSMutableDictionary alloc]init];
self.dicProductList=[[NSMutableDictionary alloc]init];
}
-(void)categoryStorage:(NSMutableArray *)arrCategory :(NSMutableDictionary *)dicCategory :(NSMutableDictionary *)dicSubCategory
{
// arrCategory =[[NSMutableArray alloc]init];
self.arrCategoryList=arrCategory;
// [self.arrCategoryList addObject:arrCategory];
// NSLog(#"inside data handler file==%#",self.arrCategoryList);
// dicCategory=[[NSMutableDictionary alloc]init];
self.dicCategoryList=dicCategory;
// dicSubCategory=[[NSMutableDictionary alloc]init];
self.dicAllSubCategoryList=dicSubCategory;
}
Here i have created the static thread and then i am trying to store all the values in to mentioned array and dictionary in other class ,once i have stored the values here then i have to access those data to any where in my app.
Is it Possible?
Is it Right Way?
Another classFile
.m
Like this i am trying to store the values in NSobject Class Array.
for(NSDictionary *DicHoleCategories in ArrCategory)
{
NSMutableDictionary *DicAllValues=[[NSMutableDictionary alloc]init];
[DicAllValues setObject:[[DicHoleCategories objectForKey:#"name"] length] !=0?[DicHoleCategories objectForKey:#"name"] :#"" forKey:#"name"];
StrName=[DicHoleCategories objectForKey:#"image"];
[DicAllValues setObject:[DicHoleCategories objectForKey:#"subcategory"] forKey:#"subcategory"];
if(StrName!=nil)
{
subimages=[NSString stringWithFormat:LocalImage"%#",StrName];
[DicAllValues setObject:subimages forKey:#"image"];
[arrImages addObject:[DicAllValues objectForKey:#"image"]];
}
[ArrName addObject:DicAllValues];
[arrSubCategory addObject:[DicAllValues objectForKey:#"subcategory"]];
[dicSubCategory setObject:[DicAllValues objectForKey:#"subcategory"] forKey:#"subcategory"];
[dicAllValues setObject:dicAllValues forKey:#"hole"];
}
[file categoryStorage:ArrCategory :dicAllValues :dicSubCategory];
OUTPUT:
Collection <__NSArrayM: 0x7f8c33c7b220> was mutated while being enumerated.'

Unable to update position in core data

I need to update position in core data base. When I add object or remove it from that base everything works fine. Problem occurs when I want to update object in that base. The problem is that program throws me:
Thread 1: EXC_BAD_ACCES(code = 2, adres = 0x38).
It's weird because it throws this error but updtades object at core data. I'm using simulator on Xcode 5. I've tried to comment line by line back in code but it hasn't helped anymore. Taking look at the address of the error and the screen shot there is no address compatible with each other. What is wrong?
Code is this:
[self insertPositionRightAfterChangeValues:name rating:[changedRate stringValue] urlMain:[newInsert urlMain] contentUrl:[newInsert contentUrl] coverUrl:[newInsert coverUrl] date:[newInsert date] type:[newInsert type] int:integer];
And the rest of this method:
-(void)insertPositionRightAfterChangeValues:(NSString *)name rating:(NSString *)rating urlMain:(NSString *)urlMain contentUrl:(NSString *)contentUrl coverUrl:(NSString *)coverUrl date:(NSString *)date type:(NSString *)type int:(int)position
{
int motherPosision = position;
//insert new one
NSManagedObjectContext *context2 = [self managedObjectContext];
Kwejki * newEntry = [NSEntityDescription insertNewObjectForEntityForName:#"Kwejki" inManagedObjectContext:context2];
newEntry.name = [[NSString alloc] initWithString: name];
newEntry.rating = [[NSString alloc] initWithString: rating];
newEntry.urlMain = [[NSString alloc] initWithString: urlMain];
newEntry.contentUrl = [[NSString alloc] initWithString: contentUrl];
newEntry.coverUrl = [[NSString alloc] initWithString: coverUrl];
newEntry.date = [[NSString alloc] initWithString: date];
newEntry.type = [[NSString alloc] initWithString: type];
NSLog(#"%#", newEntry.name);
NSLog(#"%#", newEntry.rating);
NSLog(#"%#", newEntry.urlMain);
NSLog(#"%#", newEntry.contentUrl);
NSLog(#"%#", newEntry.coverUrl);
NSLog(#"%#", newEntry.date);
NSLog(#"%#", newEntry.type);
NSError *error2;
if (![context2 save:&error2]) {
NSLog(#"Whoops, couldn't save: %#", [error2 localizedDescription]);
}
else{
NSLog(#"SAVED!!!");
}
}
And the screenshot with this error:
UPDATE:
When I comment line where I invoke method to insert new object I get following error: CoreData: error: Failed to call designated initializer on NSManagedObject class 'Kwejki'
UPDATE 2:
#interface Kwejki : NSManagedObject<NSCopying>
#property (nonatomic, strong) NSString * type;
#property (nonatomic, strong) NSString * contentUrl;
#property (nonatomic, strong) NSString * coverUrl;
#property (nonatomic, strong) NSString * rating;
#property (nonatomic, strong) NSString * urlMain;
#property (nonatomic, strong) NSString * date;
#property (nonatomic, strong) NSString * name;
#end
#implementation Kwejki
#synthesize name;
#synthesize date;
#synthesize urlMain;
#synthesize rating;
#synthesize coverUrl;
#synthesize contentUrl;
#synthesize type;
-(Kwejki *)copyWithZone:(NSZone *)zone
{
Kwejki *copyModel = [[Kwejki allocWithZone:zone] init];
if(copyModel)
{
copyModel.name = [self name];
copyModel.date = [self date];
copyModel.urlMain = [self urlMain];
copyModel.rating = [self rating];
copyModel.coverUrl = [self coverUrl];
copyModel.contentUrl = [self contentUrl];
copyModel.type = [self type];
}
return copyModel;
}
#end
-(void)addNewPosition:(ScrollViewViewController *)ScrollController recentlyDownloadedItem:(KwejkModel *)modelTmp
{
if(modelTmp == nil)
{
NSLog(#"YES NULL");
}
else
{
NSLog(#"Not null");
}
Kwejki * newEntry = [NSEntityDescription insertNewObjectForEntityForName:#"Kwejki" inManagedObjectContext:self.managedObjectContext];
NSLog(#"%#", [modelTmp getNameOfItem]);
newEntry.name = [[NSString alloc] initWithString:[modelTmp getNameOfItem]];
newEntry.rating = [modelTmp getRateOfPosition];
newEntry.urlMain = [modelTmp getUrlAdress];
newEntry.contentUrl = [modelTmp getContentUrl];
newEntry.coverUrl = [modelTmp getCoverImage];
newEntry.date = [modelTmp getDateOfItem];
if([modelTmp getType] == photo)
{
newEntry.type = #"0";
}
else if([modelTmp getType] == gif)
{
newEntry.type = #"1";
}
else if ([modelTmp getType] == video)
{
newEntry.type = #"2";
}
NSLog(#"%#", newEntry.name);
NSLog(#"%#", newEntry.rating);
NSLog(#"%#", newEntry.urlMain);
NSLog(#"%#", newEntry.contentUrl);
NSLog(#"%#", newEntry.coverUrl);
NSLog(#"%#", newEntry.date);
NSLog(#"%#", newEntry.type);
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
else{
NSLog(#"UDALO SIE!!!");
}
[modelArray insertObject:newEntry atIndex:0];
[self.tableView reloadData];
}
I've tried to overcome this problem just adding new object again as update but it also doesn't helped. How I add new object: I tap long on position, new window opens and there I add new values, invoke from that view method from Main ViewController, and here it crashes. When I add normally object as described above but in separate window everything works. I really don't know what is wrong.
When I see this error it normally mean that I did not setup my NSManageObject correctly.
Things to check:
Add a break point in your insertPositionRightAfterChangeValues method and step through to find where the exception is thrown. (My guess is when your creating your Kwejki object.)
That Kwejki is a subclass of NSManageObject.
That Kwejki entity and class name are correct. (Could you show your .xcdatamodeId entity properties for Kwejki?)
If everything is correct, then for an insanity check I would create the Kwejki object the long way.
NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([Kwejki class]) inManagedObjectContext:context2];
Kwejki* newEntry = [[Kwejki alloc] initWithEntity:entity insertIntoManagedObjectContext:context2];
Then you can see if the entity is a problem or your Kwejki is.
P.S. As a helpful suggestion instead of typing in the entity name.
Kwejki * newEntry = [NSEntityDescription insertNewObjectForEntityForName:#"Kwejki" inManagedObjectContext:context2];
I would do something like this.
Kwejki * newEntry = [NSEntityDescription entityForName:NSStringFromClass([Kwejki class]) inManagedObjectContext:context2];
This give you a compiler check for entity name.

CoreData with Singleton manager

I want to implement Core Data in my app with a Singleton Class that will manage the managed object context. I have the implementation without Core Data because I dont know how to manage everything.
Now, I have this code:
I have my ListViewController:
#interface YPProjectListViewController () {
SelectionSuccessBlock2 successBlock;
}
#property (nonatomic, strong) UITableView *tableView;
#property (nonatomic, strong) NSMutableArray * data;
#property (nonatomic, strong) UIRefreshControl *spinner ;
#end
#implementation YPProjectListViewController
#synthesize tableView;
#synthesize data;
#synthesize spinner;
- (void)viewDidLoad {
[super viewDidLoad];
spinner = [[UIRefreshControl alloc]initWithFrame:CGRectMake(130, 10, 40, 40)];
[self loadProjectsFromService];
[spinner addTarget:self action:#selector(loadProjectsFromService) forControlEvents:UIControlEventValueChanged];
[tableView addSubview:spinner];
}
-(void)loadProjectsFromService{
[spinner beginRefreshing];
self.data = [[NSMutableArray alloc] init];
[self.tableView reloadData];
[self.view addSubview:self.tableView];
__weak typeof(self) weakSelf = self;
successBlock = ^(NSMutableArray *newData) {
if ([newData count] > 0) {
[weakSelf refreshData:newData];
}
};
[spinner endRefreshing];
[ypNetManager getProjectListWithSuccessBlock:successBlock error:NULL];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Custom getter
- (UITableView *)tableView {
//custom init of the tableview
if (!tableView) {
// regular table view
tableView = [[UITableView alloc] initWithFrame:UIEdgeInsetsInsetRect(self.view.bounds, tableViewInsets) style:UITableViewStylePlain];
tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor clearColor];
return tableView;
}
return tableView;
}
#pragma mark - Private methods
- (void)refreshData:(NSMutableArray *)newData {
self.data = newData;
[self.tableView reloadData];
}
I have my AFNetworking AFHttpClient subclass with my method :
- (void)getProjectListWithSuccessBlock:(SelectionSuccessBlock2)success error:(SelectionErrorBlock)error {
NSMutableURLRequest *request = [self requestWithMethod:#"GET" path:kAPIProjectListDev parameters:nil];
[request setTimeoutInterval:kTimeOutRequest];
AFJSONRequestOperation *requestOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// NSLog(#"%# Susscess JSNON Response: %#", NSStringFromSelector(_cmd),JSON);
NSMutableArray * data = [[NSMutableArray alloc] init];
NSDictionary *projects = [JSON valueForKey:kTagProjects];
for (NSDictionary *projectDic in projects) {
[data addObject:[Project createProjectWithDictionary:projectDic]];
}
if (success) {
success(data);
}
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *aError, id JSON) {
NSLog(#"%# Failure JSNON Error%#", NSStringFromSelector(_cmd), aError);
if (error) {
error(aError);
}
}];
[self enqueueHTTPRequestOperation:requestOperation];
}
The object Project :
#property (nonatomic, strong) NSNumber *projectId;
#property (nonatomic, strong) NSString *title;
#property (nonatomic, strong) NSNumber *estimatedPrice;
and its category helper:
#implementation Project (Helper)
+ (Project *)createProjectWithDictionary:(NSDictionary *)dic {
Project *project = [[Project alloc] init];
project.projectId = [NSNumber numberWithInt:[[dic valueForKey:kTagProjectId] intValue]];
project.title = [dic valueForKey:kTagProjectTitle];
project.estimatedPrice = [NSNumber numberWithInt:[[dic valueForKey:kTagProjectEstimatedPrice] floatValue]];
// NSLog(#"Project ..... %d, Title: %#", [project.projectId intValue], project.title);
return project;
}
#end
Now, I want to use my DataSingleton Class to manage my ListViewController and my object projects in a TableView. I have the singleton. but I dont understand quite well where I have to start the managedObjectContext. or where I have to reload the TableView..
//
// DataSingleton.m
// Yeeplys
//
// Created by Carlos Roig Salvador on 8/31/13.
// Copyright (c) 2013 Carlos Roig Salvador. All rights reserved.
//
#import "DataSingleton.h"
//static instance for singleton implementation
static DataSingleton __strong *manager = nil;
//Private instance methods/properties
#interface DataSingleton()
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and
// bound to the persistent store coordinator for the application.
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's
// store added to it.
#property (readonly,strong,nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory;
#end
#implementation DataSingleton
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
//DataAccessLayer singleton instance shared across application
+ (id)sharedInstance
{
#synchronized(self)
{
if (manager == nil)
manager = [[self alloc] init];
}
return manager;
}
+ (void)disposeInstance
{
#synchronized(self)
{
manager = nil;
}
}
+(NSManagedObjectContext *)context
{
return [[DataSingleton sharedInstance] managedObjectContext];
}
//Saves the Data Model onto the DB
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
//Need to come up with a better error management here.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and
// bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil)
return __managedObjectContext;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the
// application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
return __managedObjectModel;
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"yeeplyModel"
withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc]
initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the
// application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
return __persistentStoreCoordinator;
NSURL *storeURL = [[self applicationDocumentsDirectory]
URLByAppendingPathComponent:#"MyData.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeURL options:nil error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
}
#end
To reload your table view you can attach an NSFetchedResultsController (link to Apple docs) to your view controller in order to get automatic updates every time you update your NSManagedObjectContext. There is a code in this repository made by Javi Soto that is easy to understand in order to implement the NSFetchedResultsController in your project. Take a look at JSBaseCoreDataTableViewController here.

Resources