I am trying to convert JSON array to object for display in table. I am able to capture JSON. However, when I try to turn into object, I get error shown below. There is definitely a property named "name" in object class.
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSMutableArray* latestItems = nil;
latestItems = [[NSMutableArray alloc] init];
latestItems = [json objectForKey:#"items"];
[self.tableView reloadData];
for (int i = 0; i < latestItems.count; i++)
{
NSDictionary *itemElement = latestItems[i];
// Create a new l object and set its props to todoElement properties
IDItemFromServer *newItem = [[IDItemFromServer alloc] init];
//ERROR NEXT LINE THROWS FOLLOWING ERROR
//'NSUnknownKeyException', reason: '[<IDItemFromServer 0x14e88010> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'
[newItem setValue:#"hi" forKey:#"name"];
[newItem setValue:itemElement[#"address"] forKey:#"address"];
// Add this new item to the array
[latestItems addObject:newItem];
}
Would appreciate any suggestions on how to fix error.
Edit:
//Object.h file
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface IDItemFromServer : NSObject
#property (nonatomic, retain) NSNumber * iid;
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSString * address;
#end
It says IDItemFromServer has no property name. add the name,address property like bellow code
In IDItemFromServer.h file
#import <Foundation/Foundation.h>
#interface IDItemFromServer : NSObject
#property(nonatomic,strong) NSString name;
#property(nonatomic,strong) NSString address;
#end
In IDItemFromServer.m file
#import "IDItemFromServer.h"
#implementation IDItemFromServer
#synthesize name;
#synthesize address;
#end
Related
I'm running into some trouble with a PFObject subclass. I've gone thru all of the proper setup (registering the subclass in the delegate, setting the class name, etc). But for some reason I can't get the object to load without crashing it in the view that it's supposed to be loading in.
Passing the Object
if ([segue.identifier isEqualToString:#"toPostView"])
{
pbPostViewController *postView = [pbPostViewController new];
postView = (pbPostViewController *)segue.destinationViewController;
[postView setPostToLoad:_selectedPost];
}
Receiving View.h
// Copyright (c) 2015 Chris Culos. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "PALongTextView.h"
#import "pbPost.h"
#interface pbPostViewController : UIViewController
#property (strong, nonatomic) pbPost *postToLoad;
Receiving View.m
#import "pbPost.h"
#interface pbPostViewController ()
#end
#implementation pbPostViewController
- (void)viewDidLoad {
pbPost *post = [pbPost postWithObject:_objectToLoad];
NSLog(#"post: %#", post);
// _timeStampLabel.text = post.postTimeStamp;
_userNameLabel.text = [post.postOwner valueForKey:#"username"];
_profileImage.image = [post.postOwner valueForKey:#"profileImage"];
_postDescriptionView.text = post.postDescriptionString;
_bookmarkCounterLabel.text= [NSString stringWithFormat:#"%li bookmarks", post.postBookmarkedArray.count];
_postContentView.text = #"POST CONTENT PAGE 123 456 ETC ETC ETC";
[super viewDidLoad];
//
pbPost.h
#interface pbPost : PFObject <PFSubclassing>
{
}
#property (nonatomic, retain) NSDate *postTimeStamp;
#property (nonatomic, retain) NSString *postDescriptionString;
#property (nonatomic, retain) NSString *postContentString;
#property (nonatomic, retain) NSString *postBookmarkString;
#property (nonatomic, retain) NSString *postPageCounterString;
#property (nonatomic, retain) NSArray *postBookmarkedArray;
#property (nonatomic, retain) PFFile *postOwnerProfileImage;
#property (nonatomic, retain) NSNumber *postFontSize, *totalPages;
#property (nonatomic, retain) PFUser *postOwner;
+ (pbPost *) postWithObject: (PFObject *)object;
pbPost.m
#implementation pbPost
#dynamic postContentString, postBookmarkString, postDescriptionString, postPageCounterString, postTimeStamp, commentTableView, commentButton, bookMarkButton, postOwnerProfileImage, optionsButton, postFontSize, totalPages, postBookmarkedArray, postOwner;
+ (void)load
{
[self registerSubclass];
}
+ (NSString *)parseClassName
{
return #"userPosts";
}
+ (pbPost *) postWithObject: (PFObject *)object
{
// NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// [dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
// [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
pbPost *post = [pbPost postWithObject:object];
[post fetchInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!error) {
post.postTimeStamp = [object valueForKey:#"createdAt"];
post.postDescriptionString = [object valueForKey:#"titleSummary"];
post.postFontSize = [object valueForKey:#"fontSize"];
post.postContentString = [object valueForKey:#"postContent"];
post.totalPages = [object valueForKey:#"numPages"];
post.postBookmarkedArray = [object valueForKey:#"bookmarkedBy"];
post.postOwner = [object valueForKey:#"postOwner"];
post.postOwnerProfileImage = [post.postOwner valueForKey:#"profileImage"];
NSLog(#"LOAD THE THING!: %#", post);
}
else
{
NSLog(#"Error Loading Post: %#", error);
}
}];
return post;
}
Under this circumstance; I'm getting an EXC_BAD_ACCESS at + (pbPost *)postWithObject:(PFObject *)object in the implementation file.
I feel like I'm missing something very simple here; what can it be? Thanks in advance for your help again everyone! This has stumped me for a little while and I need to get some outside help.
Since you're passing the pbPost object, you don't need to call the + (pbPost *)postWithObject:(PFObject *)object at all. To create a new instance of your PFObject subclass, you can just call:
pbPost *post = [pbPost object];
I get data from a request that has the next structure:
description
idd
name
url
photo
"result" from the NSDictionary stores info, this is the method I use.
-(void)loadLinks{
NSDictionary *dictToSend = #{#"controller": #"link",
#"action": #"loadall"
};
[ApiCaller sendDictionary: dictToSend
toURL: nil
withKey: nil
completionHandler: ^(NSDictionary *result, NSError *error) {
if (!error) {
[CommonFunctions desActivateIndicator];
DCArrayMapping *mapper = [DCArrayMapping mapperForClassElements:[JSONLink class] forAttribute:#"data" onClass:[JSONLinks class]];
DCParserConfiguration *config = [DCParserConfiguration configuration];
[config addArrayMapper:mapper];
DCKeyValueObjectMapping *parser = [DCKeyValueObjectMapping mapperForClass:[JSONLinks class] andConfiguration:config];
linksData = [parser parseDictionary: result];
[tableview reloadData];
}
}];
}
I'm using this to fill a tableview with some links. The error is the next.
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<JSONLink 0x7fc7f0c759b0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key description.'
My JSONLinks.h file:
#import <Foundation/Foundation.h>
#interface JSONLinks : NSObject
#property (nonatomic, strong) NSNumber *success;
#property (nonatomic, strong) NSArray *data;
#end
My JSONLink.h file:
#import <Foundation/Foundation.h>
#interface JSONLink : NSObject
#property (nonatomic, strong) NSNumber *idd;
#property (nonatomic, copy) NSString *name;
#property (nonatomic, copy) NSString *url;
#property (nonatomic, copy) NSString *descriptionData;
#property (nonatomic, copy) NSString *photo;
-(NSString *) urlDirection;
#end
Where is the error? :S
Thank you.
Im trying to make user role page that get data from login. I created the own delegate function to call the webservice but app getting crash due to-[__NSArrayM setRoleHistorys:]: unrecognized selector sent to instance.
Here is my code: in .m file :
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
nodeContent = [[NSMutableString alloc]init];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
arrayitems = [[NSMutableArray alloc] init];
U serRoleDataParser *userroleParser = [[UserRoleDataParser alloc] init];
// UserRole *currentStudent = (UserRole *) arrayitems;
NSString *Username = username.text;
NSLog(#"the String value%#",Username);
[userroleParser getUserHistoryForIndex:0 LoginId:username.text];
NSLog(#"the String user value %#",username.text);
userroleParser.delegate = self;
}
- (void) didrecieveData : (NSArray *) userHistories forIndex :(int) index
{
arrayitems = [[NSMutableArray alloc] init];
UserRole *roles = (UserRole *) arrayitems;
roles.RoleHistorys = userHistories;
datadisplay.text = roles.role;
NSLog(#"the Success data%#", datadisplay.text);
}
in delegate file .h
#interface UserRole : NSObject
#property (nonatomic,copy) NSString *username;
#property (nonatomic,copy) NSString *role;
#property (nonatomic,copy) NSString *empcode;
#property (nonatomic,copy)NSMutableArray * RoleHistorys;
#end
Dataparser.h file (delegate)
#import <Foundation/Foundation.h>
#import "UserRole.h"
#protocol UserRoleDataParserDelegate <NSObject>
- (void) didrecieveData : (NSArray *) userHistories forIndex :(int) index ;
#end
#interface UserRoleDataParser : NSObject<NSXMLParserDelegate>
{
NSMutableData *xmlData;
NSXMLParser *userroleParser;
NSMutableString *capturedString;
BOOL captureCharacters;
NSMutableArray *userHistories;
}
- (void) getUserHistoryForIndex : (int) index LoginId :(NSString*) loginId;
#property (weak,nonatomic) id <UserRoleDataParserDelegate> delegate;
#property (nonatomic) int index;
#end
am getting output in nslog but the app getting crash.
This code isn't correct:
arrayitems = [[NSMutableArray alloc] init];
UserRole *roles = (UserRole *) arrayitems;
You can't just cast an array to your custom class type (unless you have subclassed NSMutableArray and the instance is actually of the subclass type). You need to create an instance of or find the correct instance you want before you try to use it.
You create NSMutableArray and you cast it to UserRole object, after that you try to save data in that: roles.RoleHistorys :
arrayitems = [[NSMutableArray alloc] init];
UserRole *roles = (UserRole *) arrayitems;
roles.RoleHistorys = userHistories; //<- Error happened here
So you try to save data by calling selector setRoleHistorys on object of type NSMutableArray which you cannot do because NSMutableArray doesn't contain that property.
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
Let me preface this question by saying that I believe it to be a memory management mistake on my end. I just can't seem to figure out why it is happening.
I have a viewcontroller and a model class named Part.
#import <Foundation/Foundation.h>
#interface Part : NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) NSString *partType;
#property (nonatomic, strong) NSString *description;
#property (nonatomic, strong) NSNumber *price;
- (id)initWithName:(NSString *)name AndType:(NSString *)type;
#end
In the view controller I have a property set as follows:
#property (nonatomic, strong) Part *part;
In the init function of ViewController I create some static arrays and create objects out of them:
- (id)init {
self = [super init];
self.partList = [[NSMutableArray alloc] init];
NSArray *inputArray = #[#"Part1",
#"Part2",
#"Part3",
#"Part4",
#"Part5",
#"Part6",
#"Part7",
#"Part8"];
NSString *tempType = #"PartCategory";
// Add dummy static data
for (int i = 0; i < [inputArray count]; i++) {
Part *partInput = [[Part alloc] initWithName:[inputArray objectAtIndex:i] AndType:tempType];
//partInput.name = [inputArray objectAtIndex:i];
//partInput.partType = tempType;
NSLog(#"Inserting Part %#", partInput);
[self.partList addObject:partInput];
}
return self;
}
The NSLog I call in that loop returns Inserting Part *nil description* for every part. I just can't track down what is happening here.
EDIT: Here is the initWithName method from Part that the controller uses:
- (id)initWithName:(NSString *)name AndType:(NSString *)type {
if(self = [super init]) {
self.name = name;
self.partType = type;
}
return self;
}
When using %# to print NSObject, it calls debugDescription that by default calling the description method of that object and your Part object always have nil description.
You better solve this by changing the description property name to something else, because it conflicts with the description method of NSObject.
See also: NSObject description and debugDescription