Mapping Array to Core Data in RestKIt .20 - ios

Iam Trying To map Json To Custom Object Called Place
Managed Object Class Of Place :
#interface Place : NSManagedObject
#property (nonatomic, retain) NSString * icon;
#property (nonatomic, retain) NSString * place_id;
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSNumber * price_level;
#property (nonatomic, retain) NSNumber * rating;
#property (nonatomic, retain) NSString * vicinity;
#property (nonatomic, retain) NSString * reference;
#property (nonatomic, retain) Geometry *geometry;
#property (nonatomic, retain) Json *json;
#property (nonatomic, retain) NSSet *opening_hours;
#property (nonatomic, retain) NSSet *photos;
#property (nonatomic, retain) NSSet *types;
#end
and json in this formate :
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.870540,
"lng" : 151.1988150
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png",
"id" : "c71365287e7606bd21a3311d21fda087830b7813",
"name" : "Pancakes on the Rocks",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 1224,
"html_attributions" : [
"\u003ca href=\"https://plus.google.com/105663944571530352563\"\u003eJoshua Gilmore\u003c/a\u003e"
],
"photo_reference" : "CnRoAAAAtHLK7ii6I9RN0soDFHF9Zqu1ppyHouUPu-E_BlAP2xlJJLMJrlsBBr3ALzYZ_ysFdgDzJOc-L3NkqQ2FLk5nOAW7LNldTthkSslmbXkXqGbScwCzAwgIj_EyUQlGQjS6d7Ng36nKy_SItlejfeR8zRIQYtT--IxV_d-GfdTcebDjfhoUU7gE_ufZOBxH35EPUtUXbCJk9Gs",
"width" : 1632
}
],
"price_level" : 2,
"rating" : 3.80,
"reference" : "CoQBcgAAAI_28BshREfmXJ9UKzOLLalhpRaqcW-Wupk1-D2sgkU6ZNe1nsR0zXopB5E-_BGXO1gHxJ1IAe0l-GXzrXj9Dz31crwQ-iwNFLcBRKSGnLmEu_AgKCkfDVZIsgeGrXLNxWLOZ_U8WAZzJu5Uc9tHa9LUF2Rj1MPk9vroGcFjLGWMEhCynlHHTt_P0EZ4wSwwfsumGhQAkqN53-D4ZNjBPEr7qJXZAZMdDg",
"types" : [ "cafe", "restaurant", "food", "establishment" ],
"vicinity" : "Harbourside Shopping Centre,Darling Harbour/227 & 229-230 Darling Drive, Sydney"
},
the problem when i try to map Photos,types
i have NSManagedObject Class For Photo
#interface Photo : NSManagedObject
#property (nonatomic, retain) NSNumber * height;
#property (nonatomic, retain) NSNumber * width;
#property (nonatomic, retain) NSString * photo_reference;
#property (nonatomic, retain) NSSet *html_attributions;
#property (nonatomic, retain) Place *place;
#end
i try to map this by :
RKEntityMapping* photosMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([Photo class]) inManagedObjectStore:objectManager.managedObjectStore];
[photosMapping addAttributeMappingsFromArray:#[#"height",#"photo_reference",#"html_attributions",#"width"]];
//Add relationship between place and photos
[placeMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"photos"
toKeyPath:#"photos"
withMapping:photosMapping]];
but there was exception Or value are photos is nil
how i can map photos and types any help please

You have two arrays of objects that aren't using KVC key paths, "html_attributions" and "types." See this RestKit article for more information about mapping in this type of situation: Mapping values without key paths
However -- if you have control over the JSON structure, I recommend creating two new Objective C classes, perhaps named HtmlAttribution and Type, each with one property, create mappings for those classes and set the relationships in RestKit. If you can do this and change how your JSON comes through, it will simplify things greatly for you.
Possible new JSON structure for those classes (snippets):
"html_attributions" : [ {"attribution_data":"\u003ca
href=\"https://plus.google.com/105663944571\u003c/a\u003e"} ],
"types" : [ {"type_name":"cafe"}, {"type_name":"restaurant"},
{"type_name":"food"}, {"type_name":"establishment"} ],

Related

[__NSSingleEntryDictionaryI elements]: unrecognized selector sent to instance 0x2836c2820

Well, I should remember you I am still a beginner in iOS development with objective c. And maybe because of this, the solution is simple but I canĀ“t see it. I have a json who is armed in the following way :
{
"origin_addresses": [
"Test"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "0.3 km",
"value": 339
},
"duration": {
"text": "1 min",
"value": 82
},
"status": "OK"
}
]
}
],
"status": "OK"
}
The app can consume the service without problems. My goal is to reach the distance attribute. Which I do as follows. I use a foreach to get through the array rows and then another foreach to get through the array elements.
for (BPCGARows *item in googleAddress.rows) {
NSLog(#"rows : %#", item);
for (BPCGAElements *element in item.elements) {
}
}
When I'm debugging the app, my first for each works without problems, but when I access the second foreach the (BPCGAElements * element in item.elements) the app crashes. Finally I can't print the item.elements in a log either. The error message is as follows:
'NSInvalidArgumentException', reason: '-[__NSSingleEntryDictionaryI
elements]: unrecognized selector sent to instance 0x281c75da0'
header BPCGADistance :
#interface BPCGADistance : MBOInspectableModel
#property (nonatomic, strong, readonly) NSString *text;
#property (nonatomic, strong, readonly) NSNumber *value;
#end
main BPCGADistance:
#interface BPCGADistance()
#property (nonatomic, strong, setter=text:) NSString *text;
#property (nonatomic, strong, setter=value:) NSNumber *value;
#end
header BPCGAElements :
#interface BPCGADistance : MBOInspectableModel
#property (nonatomic, strong, readonly) NSString *text;
#property (nonatomic, strong, readonly) NSNumber *value;
#end
main BPCGAElements:
#interface BPCGADistance()
#property (nonatomic, strong, setter=text:) NSString *text;
#property (nonatomic, strong, setter=value:) NSNumber *value;
#end
This is my NSLog(#"rows : %#", item),
I emphasize that by using the item.elements to print the crashea app on the console. ;

RestKit 0.2 'NSInternalInconsistencyException', reason: 'Unable to add mapping for keyPath scheduleEntries, one already exists...'

I need some help configuring RestKit 0.2x... I am returning JSON with a Schedule object and ScheduleEntries as a nested array.
Sample JSON:
[{
"id": 3,
"name": "Schedule 9",
"sWeek": 9,
"sYear": 2014,
"companyId": 1,
"createdOn": "2014-02-11T22:01:33.547",
"modifiedOn": null,
"companyCode": "0001",
"isActive": true,
"notes": "This is a test note",
"scheduleEntries": [{
"id": 15,
"companyId": 1,
"userId": "a7e46520-8db7-4452-821d-7938b23fcd07",
"scheduleId": 3,
"jobId": 5,
"isActive": true,
"createdOn": "2014-02-11T22:01:33.993",
"modifiedOn": null,
"sWeek": 11,
"sYear": 2014,
"startTime": "2014-03-10T08:48:00",
"endTime": "2014-03-10T08:48:00"
}, {
"id": 16,
"companyId": 1,
"userId": "a7e46520-8db7-4452-821d-7938b23fcd07",
"scheduleId": 3,
"jobId": 3,
"isActive": true,
"createdOn": "2014-02-11T22:01:34.003",
"modifiedOn": null,
"sWeek": 11,
"sYear": 2014,
"startTime": "2014-03-11T00:57:00",
"endTime": "2014-03-11T00:57:00"
}, {....
NSManagedObjects
#interface Schedule : NSManagedObject
#property (nonatomic, retain) NSNumber * scheduleId;
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSNumber * sWeek;
#property (nonatomic, retain) NSNumber * sYear;
#property (nonatomic, retain) NSNumber * companyId;
#property (nonatomic, retain) NSString * companyCode;
#property (nonatomic, retain) NSString * notes;
#property (nonatomic, retain) NSNumber * isActive;
#property (nonatomic, retain) NSDate * createdOn;
#property (nonatomic, retain) NSDate * modifiedOn;
#property (nonatomic, retain) NSSet * scheduleEntries;
#end
#implementation Schedule
#dynamic scheduleId;
#dynamic name;
#dynamic sWeek;
#dynamic sYear;
#dynamic companyId;
#dynamic companyCode;
#dynamic notes;
#dynamic isActive;
#dynamic createdOn;
#dynamic modifiedOn;
#dynamic scheduleEntries;
#end
#interface ScheduleEntry : NSManagedObject
#property (nonatomic, retain) NSNumber * scheduleEntryId;
#property (nonatomic, retain) NSNumber * companyId;
#property (nonatomic, retain) NSNumber * usrId;
#property (nonatomic, retain) NSNumber * scheduleId;
#property (nonatomic, retain) NSNumber * jobId;
#property (nonatomic, retain) NSNumber * sWeek;
#property (nonatomic, retain) NSNumber * sYear;
#property (nonatomic, retain) NSDate * startTime;
#property (nonatomic, retain) NSDate * endTime;
#property (nonatomic, retain) NSNumber * isActive;
#property (nonatomic, retain) NSDate * createdOn;
#property (nonatomic, retain) NSDate * modifiedOn;
#end
#implementation ScheduleEntry
#dynamic scheduleEntryId;
#dynamic companyId;
#dynamic usrId;
#dynamic scheduleId;
#dynamic jobId;
#dynamic sWeek;
#dynamic sYear;
#dynamic startTime;
#dynamic endTime;
#dynamic isActive;
#dynamic createdOn;
#dynamic modifiedOn;
#end
Code:
RKManagedObjectStore *managedObjectStore = [RKManagedObjectStore defaultStore];
// Create mapping for entity
RKEntityMapping *scheduleEntryMapping = [RKEntityMapping mappingForEntityForName:#"ScheduleEntry" inManagedObjectStore:managedObjectStore];
scheduleEntryMapping.identificationAttributes = #[#"scheduleEntryId"];
[scheduleEntryMapping addAttributeMappingsFromDictionary:#{
#"id" : #"scheduleEntryId",
#"companyId": #"companyId",
#"usrId" : #"usrId",
#"scheduleId" : #"scheduleId",
#"jobId" : #"jobId",
#"isActive": #"isActive",
#"sWeek": #"sWeek",
#"sYear": #"sYear",
#"startTime": #"startTime",
#"endTime": #"endTime",
#"createdOn": #"createdOn",
#"modifiedOn": #"modifiedOn"
}];
RKEntityMapping *scheduleMapping = [RKEntityMapping mappingForEntityForName:#"Schedule" inManagedObjectStore:managedObjectStore];
scheduleMapping.identificationAttributes = #[#"scheduleId"];
[scheduleMapping addAttributeMappingsFromDictionary:#{
#"id" : #"scheduleId",
#"name": #"name",
#"sWeek": #"sWeek",
#"sYear": #"sYear",
#"companyId": #"companyId",
#"companyCode": #"companyCode",
#"notes": #"notes",
#"isActive": #"isActive",
#"createdOn": #"createdOn",
#"modifiedOn": #"modifiedOn",
#"scheduleEntries": #"scheduleEntries"
}];
[scheduleMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"scheduleEntries"
toKeyPath:#"scheduleEntries"
withMapping:scheduleEntryMapping]];
This code is very close to the RestKit 0.2x example but I can't seem to get it to work. I can get a single object just fine, but when it comes to objects that have nested data I'm stuck. It has been a few days working on this with no results. The error says I'm setting the keyPath more than once but I don't see it. Any help would be appreciated.
You just need to remove #"scheduleEntries": #"scheduleEntries" from the mapping dictionary on scheduleMapping because that is added (and therefore duplicated) by the relationship mapping.
Other than that things look correct.

parse json using JsonModel

Facing problem while getting a array of json.
I am using JsonModel library for json handelling.
My json data is:
[
{
"TSCard_id": 100,
"TSCardBackend_id": "TSu1t1",
"TSCard_date": "10/11/2013",
"TSCard_resource_id": "",
"TSCard_resource_name": "",
"TSCard_job_id": "JOB_M2156 ",
"TSCard_job_desc": "BAGARIA MILLIPORE - BOM ",
"TSCard_activity_id": "B03",
"TSCard_activity_desc": "Closing",
"TSCard_hours": "4.0",
"TSCard_chargeableflag": "0",
"TSCard_desc": "Description:",
"TSCard_syncflag": "0",
"TSCard_flag": "",
"user_id": "1"
},
{
"TSCard_id": 101,
"TSCardBackend_id": "TSu1t2",
"TSCard_date": "12/11/2013",
"TSCard_resource_id": "",
"TSCard_resource_name": "",
"TSCard_job_id": "JOB_B0002",
"TSCard_job_desc": "ABB LIMITED - BLR ",
"TSCard_activity_id": "NB01",
"TSCard_activity_desc": "Admin ",
"TSCard_hours": "5.0",
"TSCard_chargeableflag": "1",
"TSCard_desc": "Description:",
"TSCard_syncflag": "0",
"TSCard_flag": "",
"user_id": "1"
}
]
Above json has 2 objects of type TSCard class
//TSCard.h
#import <Foundation/Foundation.h>
#import <JSONModel.h>
#protocol TSCard #end
#interface TSCard : JSONModel
#property (nonatomic, retain) NSString *TSCard_id;
#property (nonatomic, retain) NSString *TSCardBackend_id;
#property (nonatomic, retain) NSString *TSCard_date;
#property (nonatomic, retain) NSString *TSCard_resource_id;
#property (nonatomic, retain) NSString *TSCard_resource_name;
#property (nonatomic, retain) NSString *TSCard_job_id;
#property (nonatomic, retain) NSString *TSCard_job_desc;
#property (nonatomic, retain) NSString *TSCard_activity_id;
#property (nonatomic, retain) NSString *TSCard_activity_desc;
#property (nonatomic, retain) NSString *TSCard_hours;
#property (nonatomic, retain) NSString *TSCard_chargeableflag;
#property (nonatomic, retain) NSString *TSCard_desc;
#property (nonatomic, retain) NSString *TSCard_syncflag;
#property (nonatomic, retain) NSString *TSCard_flag;
#property (nonatomic, retain) NSString *user_id;
#end
And I am making a class for array of type TSCard
//GetCardData.h
#import <JSONModel.h>
#import "TSCard.h"
#interface GetCardData : JSONModel
#property(strong,nonatomic)NSArray<TSCard>* myDataArray;
#end
then I parsing json as below:
NSError* err = nil;
GetCardData *c = [[GetCardData alloc] initWithString:jsonString error:&err];
NSLog(#"%d",c.myDataArray.count);
NSLog Error:
Error Domain=JSONModelErrorDomain Code=1 "Invalid JSON data: Attempt to initialize JSONModel object using initWithDictionary:error: but the dictionary parameter was not an 'NSDictionary'." UserInfo=0x8265490 {NSLocalizedDescription=Invalid JSON data: Attempt to initialize JSONModel object using initWithDictionary:error: but the dictionary parameter was not an 'NSDictionary'.}
I can't find where I am wrong...can anybody suggest the right way of using JsonModel and parsing a jsonString to array of TSCard objects correctly.
Try using following code for parsing your json and getting array
NSMutableArray *yourArray = [TSCard arrayOfModelsFromDictionaries:jsonString];
Than create and assign
GetCardData *objCardData = [[GetCardData alloc] init];
objCardData.myDataArray = yourArray;
or you need to change your JSONString as follow
{
"myDataArray": [
{
"TSCard_id": 100,
"TSCardBackend_id": "TSu1t1",
"TSCard_date": "10/11/2013",
"TSCard_resource_id": "",
"TSCard_resource_name": "",
"TSCard_job_id": "JOB_M2156 ",
"TSCard_job_desc": "BAGARIA MILLIPORE - BOM ",
"TSCard_activity_id": "B03",
"TSCard_activity_desc": "Closing",
"TSCard_hours": "4.0",
"TSCard_chargeableflag": "0",
"TSCard_desc": "Description:",
"TSCard_syncflag": "0",
"TSCard_flag": "",
"user_id": "1"
},
{
"TSCard_id": 101,
"TSCardBackend_id": "TSu1t2",
"TSCard_date": "12/11/2013",
"TSCard_resource_id": "",
"TSCard_resource_name": "",
"TSCard_job_id": "JOB_B0002",
"TSCard_job_desc": "ABB LIMITED - BLR ",
"TSCard_activity_id": "NB01",
"TSCard_activity_desc": "Admin ",
"TSCard_hours": "5.0",
"TSCard_chargeableflag": "1",
"TSCard_desc": "Description:",
"TSCard_syncflag": "0",
"TSCard_flag": "",
"user_id": "1"
}
]
}
Than your code will definitely work. Tell me if need more help.
For your problem, I personally recommend BWJSONMatcher. You don't have to do anything else or declare any protocol apart from your data model:
#interface TSCard : NSObject
#property (nonatomic, strong) NSString *TSCard_id;
#property (nonatomic, strong) NSString *TSCardBackend_id;
#property (nonatomic, strong) NSString *TSCard_date;
#property (nonatomic, strong) NSString *TSCard_resource_id;
#property (nonatomic, strong) NSString *TSCard_resource_name;
#property (nonatomic, strong) NSString *TSCard_job_id;
#property (nonatomic, strong) NSString *TSCard_job_desc;
#property (nonatomic, strong) NSString *TSCard_activity_id;
#property (nonatomic, strong) NSString *TSCard_activity_desc;
#property (nonatomic, strong) NSString *TSCard_hours;
#property (nonatomic, strong) NSString *TSCard_chargeableflag;
#property (nonatomic, strong) NSString *TSCard_desc;
#property (nonatomic, strong) NSString *TSCard_syncflag;
#property (nonatomic, strong) NSString *TSCard_flag;
#property (nonatomic, strong) NSString *user_id;
#end
You can then get your array with one neatly short line:
NSArray *dataArray = [BWJSONMatcher matchJSON:jsonString withClass:[TSCard class]];
You can using this method in JSONModel
NSError *error;
NSMutableArray <TSCard *> *yourArray = [TSCard arrayOfModelsFromString:strData error:&error];
and do your logic.

Attribute of relationship in Core Data is returning nil when being called in iOS

I have an iOS application where I am using Core Data for storage. I have two entities ("MyEntity", and "OtherEntity") which are in a one to one relationship. Both entities are related to each other (i.e. each entity has an inverse relationship with the other). In addition to having a relationship with each other, one of the attributes of each entity is also the primarykey of the other entity.
The problem I am having is that I realize that I shouldn't have an attribute that is the foreign key of another entity, when the entities have a relationship with each other, however I am unable to retrieve the primary key indirectly by referencing the relationship attribute, but I am able to retrieve it by referencing the attribute that I explicitly set to the primary key of the other entity:
//NSInteger userId = [testUser.otherEntity.userId integerValue]; --> returns nil
NSInteger userId = [testUser.userId integerValue]; --> works fine
where "testUser" is an instance of type "MyEntity" which is a subclass of NSManagedObject, and "otherEntity" is an instance of the Entity, "OtherEntity" that has an inverse relationship with "MyEntity".
Here are the attributes of each Entity:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class OtherEntity;
#interface MyEntity : NSManagedObject
#property (nonatomic, strong) NSString * email;
#property (nonatomic, strong) NSNumber * primaryId; //primary key for MyEntity
#property (nonatomic, strong) NSString * metaData;
#property (nonatomic, strong) NSDate * birthDate;
#property (nonatomic, strong) NSString * name;
#property (nonatomic, strong) NSNumber * userId; //this is the primary key for OtherEntity
#property (nonatomic, strong) OtherEntity *otherEntity;
#end
and here are the attributes for OtherEntity:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class MyEntity;
#interface OtherEntity : NSManagedObject
#property (nonatomic, strong) NSString * address;
#property (nonatomic, strong) NSString * city;
#property (nonatomic, strong) NSString * country;
#property (nonatomic, strong) NSString * fax;
#property (nonatomic, strong) NSString * phone;
#property (nonatomic, strong) NSString * postalCode;
#property (nonatomic, strong) NSString * province;
#property (nonatomic, strong) NSNumber * myUserId//primary key of MyEntity
#property (nonatomic, strong) NSNumber * userId;//primary key of Other Entity
#property (nonatomic, strong) MyEntity *myEntity;
#end
What is it that I'm doing wrong?
(From the comments:) You did not set a relationship for testUser,
Therefore testUser.otherEntity is nil.
Then testUser.otherEntity.userId is also nil and [testUser.otherEntity.userId integerValue] return zero.

ios : how to insert null value into sqlite with fmdb

my sqlite table structure is :
CREATE TABLE "location" ("latitude" DOUBLE,"longitude" DOUBLE,"date" DATETIME,"locationDescription" VARCHAR,"photopath" VARCHAR,"placemark" BLOB,"wheelId" INTEGER,"wheelSize" DOUBLE,"frontWheelx" DOUBLE,"frontWheely" DOUBLE,"rearWheelx" DOUBLE,"rearWheely" DOUBLE)
and now I want to insert one record into the table, insert column : ( date , photopath , wheelId , wheelSize , frontWheelx , frontWheely , rearWheelx , rearWheely ) and ignore column : (latitude , longitude , locationDescription , placemark)
my code is :
BOOL succeed = [lunGaiDataBase executeUpdate:#"insert into location (date, photopath, wheelid, wheelsize, frontwheelx, frontwheely, rearwheelx, rearwheely) values(?,?,?,?,?,?,?,?)",
location.date,location.photoPath, location.wheelId,location.wheelSize,location.frontWheelx,location.frontWheely,location.rearWheelx,location.rearWheely];
my location class is :
#property (nonatomic, assign) double latitude;
#property (nonatomic, assign) double longitude;
#property (nonatomic, retain) NSDate * date;
#property (nonatomic, retain) NSString * locationDescription;
#property (nonatomic, retain) NSString * photoPath;
//#property (nonatomic, retain) NSString * category;
#property (nonatomic, retain) CLPlacemark * placemark;
#property (nonatomic, assign) NSInteger wheelId;
#property (nonatomic, assign) double frontWheelx;
#property (nonatomic, assign) double frontWheely;
#property (nonatomic, assign) double rearWheelx;
#property (nonatomic, assign) double rearWheely;
#property (nonatomic, assign) double wheelSize;
when I run the program, it crashed !! Help me !!
If i've not mistaken, your crash message would be something like "EXC_BAD_EXCESS" right?
Try this :
BOOL succeed = [lunGaiDataBase executeUpdate:#"insert into location (wheelId) values(?)",
[NSNumber numberWithInt:location.wheelId]];
Since wheelId is declared as NSInteger, you've got to pass it as
[NSNumber numberWithInt:location.wheelId]

Resources