retrieve RLMObject where value exist in RLMArray<RLMString*> in iOS - ios

i create Stock_RLM : RLMObject and Stock_RLM have RLMArray of RLMString.
i want filer RLMObject using RLMArray's Value. It's Possible?
#import <Realm/Realm.h>
#interface Stock_RLM : RLMObject
#property NSString *_id;
#property NSString *code;
#property NSString *name;
#property NSString *full_name;
#property NSString *type;
#property RLMArray<RLMString> *stock_sectors;
#end
RLM_ARRAY_TYPE(Stock_RLM)
My RLMObject is : -
Stock_RLM {
_id = 5b60554726f2fe334cad881d;
code = GRASIM;
name = GRASIM;
full_name = Grasim Industries Limited;
type = NSE;
stock_sectors = RLMArray<string> <0x1c4114d00> (
[0] 5b6046d1f1e8972b9cebd584,
[1] 5b6046d1f1e8972b9cebd586,
[2] 5b6046d1f1e8972b9cebd587,
[3] 5b6046d1f1e8972b9cebd588,
[4] 5b6046d1f1e8972b9cebd59a,
[5] 5b6046d1f1e8972b9cebd5c1
);
}
i Want to filter '5b6046d1f1e8972b9cebd584'exist in RLMArray in RLMObject or Not.

in your **.h
#interface TESTClass:NSObject
#property NSString *_id;
#property NSString *_code;
#property NSString *_name;
#property NSArray *theStrArr;
#end
in your **.m
#implementation TESTClass
#end
in somewhere you test
TESTClass *obje1 = [[TESTClass alloc] init];
TESTClass *obje2 = [[TESTClass alloc] init];
TESTClass *obje3 = [[TESTClass alloc] init];
obje1.theStrArr = [NSArray arrayWithObjects:#"11",#"22",#"33",nil];
obje2.theStrArr = [NSArray arrayWithObjects:#"44",#"55",#"66",nil];
obje3.theStrArr = [NSArray arrayWithObjects:#"77",#"88",#"99",nil];
NSArray *totalArr = [NSArray arrayWithObjects:obje1,obje2,obje3, nil];
NSString *testStr = [NSString stringWithFormat:#"22"];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"theStrArr CONTAINS %#",testStr];
NSArray *resultArr = [totalArr filteredArrayUsingPredicate:pred];
CLog(#"the result arr %#",resultArr);

Related

Initialization wrong class

i class
Collections *tempLocalCollection = [[Collections alloc] init];
the problem is that when I try to promote an attribute in sequent way
tempLocalCollection.id = [f numberFromString:[NSString stringWithFormat:#"%#", #"0"]];
tempLocalCollection.action = #"client_insert";
I should be in error
-[Collections setId:]: unrecognized selector sent to instance 0xff8afb0 2015-09-16 10:25:14.235 App[1042:128375] ***
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[Collections setId:]:
unrecognized selector sent to instance 0xff8afb0'
where am I wrong ?
Collections.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class Items;
#interface Collections : NSManagedObject
#property (nonatomic, retain) NSNumber * datetime_creation;
#property (nonatomic, retain) NSNumber * datetime_last_update_client;
#property (nonatomic, retain) NSNumber * datetime_last_update_server;
#property (nonatomic, retain) NSString * local_delete;
#property (nonatomic, retain) NSNumber * id;
#property (nonatomic, retain) NSString * action;
#property (nonatomic, retain) NSString * label;
#property (nonatomic, retain) NSString * labelServer;
#property (nonatomic, retain) NSNumber * ref_user;
#property (nonatomic, retain) NSNumber * sorting;
#property (nonatomic, retain) NSNumber * system;
#property (nonatomic, retain) NSSet *collection_item;
#end
#interface Collections (CoreDataGeneratedAccessors)
#end
Collections.m
#import "Collections.h"
#import "Items.h"
#implementation Collections
#dynamic datetime_creation;
#dynamic datetime_last_update_client;
#dynamic datetime_last_update_server;
#dynamic local_delete;
#dynamic action;
#dynamic id;
#dynamic label;
#dynamic labelServer;
#dynamic ref_user;
#dynamic sorting;
#dynamic system;
#dynamic collection_item;
#end
This is the method that uses the class and where it goes wrong.
I think the context is the same right?
-(Collections *) upgrateListCollection:(NSDictionary *) coll{
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *id = [f numberFromString:[NSString stringWithFormat:#"%#", coll[#"id"]]];
Collections *tempLocalCollection = [[Collections alloc] init];
NSArray *tmp = [Collections MR_findByAttribute:#"id" withValue:id];
if(tmp.count != 0){
tempLocalCollection = tmp[0];
}
if(!tempLocalCollection.isAccessibilityElement){
tempLocalCollection.id = [f numberFromString:[NSString stringWithFormat:#"%#", #"0"]];
tempLocalCollection.action = #"client_insert";
}else{
if([tempLocalCollection.local_delete isEqual: #"1"]){
tempLocalCollection.action = #"client_delete";
}else{
if([tempLocalCollection.label isEqual:coll[#"label"]]){
if(tempLocalCollection.datetime_last_update_client < coll[#"datetime_last_update_server"]){
tempLocalCollection.action = #"client_update";
}else{
tempLocalCollection.action = #"server_update";
}
}
}
}
if(tempLocalCollection != nil){
tempLocalCollection.labelServer = coll[#"label"];
tempLocalCollection.datetime_last_update_server = coll[#"datetime_last_update_server"];
tempLocalCollection.datetime_creation = coll[#"creation_utc_server"];
}
return tempLocalCollection;
}
NSManagedObject subclass (Collections) properties are dynamic, their setter and getter are generated at runtime
Thus when you create object of Collections using alloc/init in that case the dynamic properties are not created hence you get the exception unrecognized selector sent to instance
The right way of creating a NSManagedObject is
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Collections" inManagedObjectContext:myMOC];
Collections *collection = (Collections *)[[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:myMOC];
And if you want to create a temporary object of Collections then pass nil as manage object context
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Collections" inManagedObjectContext:myMOC];
Collections *tempObj = (Collections *)[[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
That is a managed object and needs to be created in its managing context.

NSUserdefaults not working with NSKeyedArchiver

I have a NSMutableArray filled with objects of my Movie class wich i want to save but it doesn't work and i can not figure out why...
Movie.h:
#interface Movie : NSObject <NSCoding>{
NSString *name;
int year;
int length;
NSString *file_size;
int rating;
NSArray *genre;
NSString *plot;
}
#property (nonatomic, retain) NSString *name;
#property (nonatomic, assign) int year;
#property (nonatomic, assign) int length;
#property (nonatomic, retain, retain) NSString *file_size;
#property (nonatomic, assign) int rating;
#property (nonatomic, retain) NSArray *genre;
#property (nonatomic, retain) NSString *plot;
-(id) initWithName:(NSString*)newName year:(int)newYear length:(int)newLength filesize:(NSString*)newFileSize rating:(int)newRating genre:(NSArray*)newGenre plot:(NSString*)newPlot;
- (void) encodeWithCoder : (NSCoder *)encode ;
- (id) initWithCoder : (NSCoder *)decode;
#end
Movie.m:
#implementation Movie
#synthesize name;
#synthesize year;
#synthesize length;
#synthesize file_size;
#synthesize rating;
#synthesize genre;
#synthesize plot;
-(id)initWithName:(NSString *)newName year:(int)newYear length:(int)newLength filesize:(NSString *)newFileSize rating:(int)newRating genre:(NSArray *)newGenre plot:(NSString *)newPlot{
self.name = newName;
self.year = newYear;
self.length = newLength;
self.file_size = newFileSize;
self.rating = newRating;
self.genre = newGenre;
self.plot = newPlot;
return self;
}
- (void)encodeWithCoder:(NSCoder *)encode;
{
[encode encodeObject:name forKey:#"name"];
[encode encodeInt32:year forKey:#"year"];
[encode encodeInt32:length forKey:#"length"];
[encode encodeObject:file_size forKey:#"file_size"];
[encode encodeInt32:rating forKey:#"rating"];
[encode encodeObject:genre forKey:#"genre"];
[encode encodeObject:plot forKey:#"plot"];
}
- (id)initWithCoder:(NSCoder *)decode;
{
NSString *name_decode = [decode decodeObjectForKey:#"name"];
int year_decode = [decode decodeInt32ForKey:#"year"];
int length_decode = [decode decodeInt32ForKey:#"length"];
NSString *file_size_decode = [decode decodeObjectForKey:#"file_size"];
int rating_decode = [decode decodeInt32ForKey:#"rating"];
NSArray *genre_decode = [decode decodeObjectForKey:#"genre"];
NSString *plot_decode =[decode decodeObjectForKey:#"plot"];
return [self initWithName:name_decode year:year_decode length:length_decode filesize:file_size_decode rating:rating_decode genre:genre_decode plot:plot_decode];
}
#end
Save Action (Movies is the NSMutableArray containing my Objects):
NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
NSData *encodedData = [NSKeyedArchiver archivedDataWithRootObject:Movies];
[userDefault setObject:encodedData forKey:[NSString stringWithFormat:#"MOVIES"]];
Load Action:
NSData *decodedData = [userDefault objectForKey: [NSString stringWithFormat:#"MOVIES"]];
NSArray *decodedArray =[NSKeyedUnarchiver unarchiveObjectWithData: decodedData];
The returned Array is always (null)... i have no clue
I tried several different kind of code snippets i found on the internet and/or stackoverflow
Your Movie initWithName... method is incorrect. It needs to be:
- (instancetype)initWithName:(NSString *)newName year:(int)newYear length:(int)newLength filesize:(NSString *)newFileSize rating:(int)newRating genre:(NSArray *)newGenre plot:(NSString *)newPlot {
self = [super init];
if (self) {
self.name = newName;
self.year = newYear;
self.length = newLength;
self.file_size = newFileSize;
self.rating = newRating;
self.genre = newGenre;
self.plot = newPlot;
}
return self;
}
Also, you seem to be following a very out-of-date tutorial.
You don't need to declare the ivars for your properties.
You don't need the calls to #synthesize.
You should be using ARC instead of MRC, Therefore your retain properties should be strong (thought the NSString properties should be copy.
Your init methods should return instancetype, not id.
With all of that in mind, your Movie class should be as follows:
Movie.h
#interface Movie : NSObject <NSCoding>
#property (nonatomic, copy) NSString *name;
#property (nonatomic, assign) int year;
#property (nonatomic, assign) int length;
#property (nonatomic, copy) NSString *file_size;
#property (nonatomic, assign) int rating;
#property (nonatomic, strong) NSArray *genre;
#property (nonatomic, copy) NSString *plot;
- (instancetype)initWithName:(NSString *)newName year:(int)newYear length:(int)newLength filesize:(NSString *)newFileSize rating:(int)newRating genre:(NSArray *)newGenre plot:(NSString *)newPlot;
#end
Movie.m
#implementation Movie
- (instancetype)initWithName:(NSString *)newName year:(int)newYear length:(int)newLength filesize:(NSString *)newFileSize rating:(int)newRating genre:(NSArray *)newGenre plot:(NSString *)newPlot {
self = [super init];
if (self) {
_name = newName;
_year = newYear;
_length = newLength;
_file_size = newFileSize;
_rating = newRating;
_genre = newGenre;
_plot = newPlot;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encode;
{
[encode encodeObject:self.name forKey:#"name"];
[encode encodeInt32:self.year forKey:#"year"];
[encode encodeInt32:self.length forKey:#"length"];
[encode encodeObject:self.file_size forKey:#"file_size"];
[encode encodeInt32:self.rating forKey:#"rating"];
[encode encodeObject:self.genre forKey:#"genre"];
[encode encodeObject:self.plot forKey:#"plot"];
}
- (instancetype)initWithCoder:(NSCoder *)decode;
{
NSString *name_decode = [decode decodeObjectForKey:#"name"];
int year_decode = [decode decodeInt32ForKey:#"year"];
int length_decode = [decode decodeInt32ForKey:#"length"];
NSString *file_size_decode = [decode decodeObjectForKey:#"file_size"];
int rating_decode = [decode decodeInt32ForKey:#"rating"];
NSArray *genre_decode = [decode decodeObjectForKey:#"genre"];
NSString *plot_decode =[decode decodeObjectForKey:#"plot"];
return [self initWithName:name_decode year:year_decode length:length_decode filesize:file_size_decode rating:rating_decode genre:genre_decode plot:plot_decode];
}
#end
You don't show how you create and populate your Movies variable (which should be named movies, not Movies. Make sure it isn't nil.
Also, don't needlessly use stringWithFormat.
Your saving code should be:
NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
NSData *encodedData = [NSKeyedArchiver archivedDataWithRootObject:movies];
[userDefault setObject:encodedData forKey:#"MOVIES"];
and your loading code should be:
NSData *decodedData = [userDefault objectForKey:#"MOVIES"];
NSArray *decodedArray = [NSKeyedUnarchiver unarchiveObjectWithData: decodedData];
A quick test is to see if the mutable array is actually not nil itself. Try outputting the mutable array before setting it in userDefaults.
Make sure the mutable array is initialized before trying to add objects to it.
movies = [[NSMutableArray alloc] init];

Can't store object in array

This is Apprecord class
#interface AppRecord : NSObject
#property (nonatomic, strong) NSString *appIcon;
#property (nonatomic, strong) NSString * name;
#property (nonatomic, strong) NSString * description;
#property (nonatomic, strong) NSString * location;
#property (nonatomic, strong) NSString * address;
#property (nonatomic, strong) NSString * contacts;
#property (nonatomic, strong) NSString * additional_info;
#property (nonatomic, strong) NSString * image;
#end
and I am parsing json adding to an object of App record class
#import "ParserClass.h"
#import "AppRecord.h"
#interface ParserClass ()
#property (nonatomic, strong) NSArray *appRecordList;
#property (nonatomic, strong) NSData *dataToParse;
#property (nonatomic, strong) NSMutableArray *workingArray;
#property (nonatomic, strong) AppRecord *workingEntry;
#property (nonatomic, strong) NSMutableString *workingPropertyString;
#property (nonatomic, strong) NSArray *elementsToParse;
#property (nonatomic, readwrite) BOOL storingCharacterData;
#end
#implementation ParserClass
- (id)initWithData:(NSData *)data
{
self = [super init];
if (self != nil)
{
_dataToParse = data;
}
return self;
}
- (void)main
{
self.workingArray = [NSMutableArray array];
self.workingPropertyString = [NSMutableString string];
self.workingArray=[[NSMutableArray alloc]init];
NSDictionary *allData=[NSJSONSerialization JSONObjectWithData:_dataToParse options:0 error:nil];
NSLog(#"%#",allData);
for (NSDictionary *dict in allData)
{
NSLog(#"dict====%#",dict);
self.workingEntry=[[AppRecord alloc]init];
self.workingEntry.name=[dict objectForKey:#"name"];
self.workingEntry.description=[dict objectForKey:#"description"];
self.workingEntry.location=[dict objectForKey:#"location"];
self.workingEntry.address=[dict objectForKey:#"address"];
self.workingEntry.contacts=[dict objectForKey:#"contacts"];
self.workingEntry.additional_info=[dict objectForKey:#"additional_info"];
self.workingEntry.image=[dict objectForKey:#"image"];
[self.workingArray addObject:self.workingEntry];
}
NSLog(#"WORKING ARRAY========%#",self.workingArray);// Not getting proper value of working array
self.workingArray = nil;
self.workingPropertyString = nil;
self.dataToParse = nil;
}
#end
My problem is not getting proper value of working array,it only stores description property,but it should store apprecord object,please help.
OUTPUT
alldata=
(
{
"additional_info" = "lOREN iPSUM";
address = "1972 Hillview St. Sarasota,FL 34239";
contacts = 8745674556;
description = "Very cute place, awesome wait staff, great food. I am here on vacation and it was an awesome place to go to after a day relaxing at the beach.";
id = 1;
image = "http://..";
location = "1972 Hillview St. Sarasota,FL 34239";
name = "Beer Tasting at Hurricane Hanks";
},
{
"additional_info" = gdfgdfg;
address = "Farrer Place, Sydney, New South Wales, Australia";
contacts = 3423423423423;
description = restataurant;
id = 16;
image = "http://..";
location = kolkata;
name = "mosco ";
}
)
WORKING ARRAY========(
"Very cute place, awesome wait staff, great food. I am here on vacation and it was an awesome place to go to after a day relaxing at the beach.",
restataurant
)
First object name== Beer Tasting at Hurricane Hanks
First you remove 2 time intialization of self.workingArray
And please replace
#property (nonatomic, strong) NSString * description;
deccription with some other name
To know the reason click this link
for (NSDictionary *dict in allData)
{
AppRecord *createAppRecord=[[AppRecord alloc]init];
//Do some thing
[self.workingArray addObject:createAppRecord];
}
I think it will be helpful to you.

Error after trying to serialize with JSONModel: Invalid type in JSON write (...)

i'am trying to serialize my object with the Framework JSOSNModel. But i am getting the following error:
[JSONModel.m:915] EXCEPTION: Invalid type in JSON write
(DienstleistungModel)
Here is my Sourcecode:
buchung.m
-(NSMutableArray *) FetchDienstleistungenImWarenkorb
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [app managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Warenkorb" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:#"vondatum" ascending:YES];
NSArray *sortArray = [NSArray arrayWithObjects:sort1, nil];
[request setSortDescriptors:sortArray];
NSError *error;
NSArray *fetchedObjects = [[app managedObjectContext]executeFetchRequest:request error:&error];
if (fetchedObjects == nil) {
NSLog(#"Houston, we have a problem: %#", error);
}
DienstleistungModel *dm = [[DienstleistungModel alloc]init];
NSMutableArray *produkt = [[NSMutableArray alloc]init];
for (NSArray *event in fetchedObjects) {
dm.dienstleistungid = [event valueForKey:#"produktid"];
dm.vondatum = [event valueForKey:#"vondatum"];
dm.bisdatum = [event valueForKey:#"bisdatum"];
dm.menge = [event valueForKey:#"menge"];
[produkt addObject:dm];
}
return product; // Here iam getting a list of products, saved in a mutable array
}
(IBAction)nextPressed:(id)sender {
Booking *aktuellebuchung = [[Booking alloc]init];
aktuellebuchung.bestuhlungsid = #"3";
aktuellebuchung.vondatum = self.vonDatumLabel.text;
aktuellebuchung.bisdatum = self.bisDatumLabel.text;
aktuellebuchung.thema = self.themaTextView.text;
aktuellebuchung.personenanzahl = self.anzahlPersonenLabel.text;
aktuellebuchung.veranstalter = self.veranstalterLabel.text;
aktuellebuchung.dienstetest = [self FetchDienstleistungenImWarenkorb];
NSString *test = [aktuellebuchung toJSONString]; // Here is the error
booking.h
#interface Booking : JSONModel
#property (nonatomic, retain) NSString * bestuhlungsid;
#property (nonatomic, retain) NSString * bisdatum;
#property (nonatomic, retain) NSString * vondatum;
#property (nonatomic, retain) NSString * personenanzahl;
#property (nonatomic, retain) NSString * thema;
#property (nonatomic, retain) NSString * veranstalter;
#property (nonatomic, retain) NSMutableArray * dienstetest;
#end
DienstleistungModul.h
#protocol DienstleistungModel #end
#interface DienstleistungModel : JSONModel
#property (nonatomic, retain) NSNumber * dienstleistungid;
#property (nonatomic, retain) NSString * bisdatum;
#property (nonatomic, retain) NSString * vondatum;
#property (nonatomic, retain) NSNumber * menge;
#end
you can see in the screenshot that the objects are there but i can't serialize it. please help.
I just had the same kind of problem, the problem is the following :
#property (nonatomic, retain) NSMutableArray * dienstetest;
This has to be change to specify the type of object you have in your Array so something like this will make it works (assuming it's the good object because my german isn't this good) - you already have the protocol so you should be able to specify the type with this:
#property (nonatomic, retain) NSArray<DienstleistungModel> * dienstetest;

Serialize custom object to JSON which contains NSMutableArray

I'm trying to serialize my Cart object which has an NSMutableArray of items in it but getting an:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Item)'
If I'm understanding how this is supposed to work, I need to create an Array of Dictionaries in order for NSJSONSerialization to work correctly. Is that not what I am doing below?
My Cart.h:
#interface Cart : BaseObject
#property (nonatomic, strong) NSString *comp;
#property (nonatomic, strong) NSString *sono;
#property (nonatomic, strong) NSString *cust;
#property (nonatomic, strong) NSString *scus;
#property (nonatomic, strong) NSString *cnid;
#property (nonatomic, strong) NSString *dldt;
#property (nonatomic, strong) NSString *whse;
#property (nonatomic, strong) NSString *pono;
#property (nonatomic, strong) NSString *pon2;
#property (nonatomic, strong) NSString *emad;
#property (nonatomic, strong) NSString *pkin;
#property (nonatomic, strong) NSString *comt;
#property (nonatomic, strong) NSString *rtin;
#property (nonatomic, strong) NSString *lbfg;
#property (nonatomic, strong) NSString *containsOpenPriced;
#property (nonatomic, strong) NSString *totalProductAmount;
#property (nonatomic, strong) NSMutableArray *items;
#property (nonatomic) BOOL *isSubmitting;
#end
My Cart.m:
#implementation Cart
#synthesize comp;
#synthesize sono;
#synthesize cust;
#synthesize scus;
#synthesize cnid;
#synthesize dldt;
#synthesize whse;
#synthesize pono;
#synthesize pon2;
#synthesize emad;
#synthesize pkin;
#synthesize comt;
#synthesize rtin;
#synthesize lbfg;
#synthesize containsOpenPriced;
#synthesize totalProductAmount;
#synthesize items;
- (id) initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
self.comp = dictionary[#"comp"];
self.sono = dictionary[#"sono"];
self.cust = dictionary[#"cust"];
self.scus = dictionary[#"scus"];
self.cnid = dictionary[#"cnid"];
self.dldt = dictionary[#"dldt"];
self.whse = dictionary[#"whse"];
self.pono = dictionary[#"pono"];
self.pon2 = dictionary[#"pon2"];
self.emad = dictionary[#"emad"];
self.pkin = dictionary[#"pkin"];
self.comt = dictionary[#"comt"];
self.rtin = dictionary[#"rtin"];
self.lbfg = dictionary[#"lbfg"];
self.containsOpenPriced = dictionary[#"containsOpenPriced"];
self.totalProductAmount = dictionary[#"totalProductAmount"];
NSArray *itemsArray = dictionary[#"items"];
NSMutableArray *itemsMutableArray = [[NSMutableArray alloc]init];
for (NSDictionary *itemDictionary in itemsArray) {
Item *item = [[Item alloc] initWithDictionary:itemDictionary];
[itemsMutableArray addObject:item];
}
self.items = itemsMutableArray;
}
return self;
}
#end
My code for serializing my object:
NSMutableArray *itemsToSerialize = [[NSMutableArray alloc] init];
for (Item *item in cart.items) {
NSMutableDictionary *itemDict = [[NSMutableDictionary alloc] init];
[itemDict setObject:item forKey:#"item"];
[itemsToSerialize addObject:item];
}
NSMutableDictionary *data = [#{
#"comp" : cart.comp,
#"rtin" : cart.rtin,
#"pono" : cart.pono,
#"pon2" : cart.pon2,
#"totalProductAmount" : totalProductAmount,
#"sono" : cart.sono,
#"emad" : cart.emad,
#"lbfg" : lbfg,
#"pkin" : cart.pkin,
#"containsOpenPriced" : containsOpenPriced,
#"cnid" : cart.cnid,
#"whse" : cart.whse,
#"scus" : cart.scus,
#"dldt" : cart.dldt,
#"cust" : cart.cust,
#"comt" : cart.comt,
#"items": itemsToSerialize
} mutableCopy];
NSString *command = #"shoppingCart.update";
NSMutableDictionary *request = [#{
#"command" : command,
#"comp" : cart.comp,
#"cnid" : sessionController.operator.cnid,
#"cust" : cart.cust,
#"data" : data
} mutableCopy];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:request options:kNilOptions error:nil];
This dies on the above NSJSONSerialization line. What am I missing?
This line: [itemsToSerialize addObject:item]; should be [itemsToSerialize addObject:itemDict];. The result is that you're trying to serialize an array of the items themselves, which gives the exception you're seeing.
NSJSONSerialization only works on arrays (NSArray or NSMutableArray), dictionaries (NSDictionary or NSMutableDictionary, strings (NSString or NSMutableString), and NSNumber.
The common mechanism is to create a - (NSDictionary *)serialize method on your class that copies all its values into a dictionary to be passed into NSJSONSerialization. Then implement - (id)initFromSerialization:(NSDictionary *)serialization to deserialize the object.
I know this is kinda late but maybe this class can ease your coding:
Its a class that transform Custom NSObject to JSON readable object(NSArray or NSDictionary). Have a try and see. It has the capability to skip properties and changed property type from string to NSInteger or Float, it can also changed the final output property name lets say
CustomObject *X;
X.property1 = #"Test";
//and the output JSON readable format you want tot change X to Y
//CustomObject converted to readable format
{Y = #"Test"}
here is the class Disassembler

Resources