I am trying to save an NSMutableArray in CoreData. The Array contains objects NSDictionary
NSDictionary has following Structure
valueDict =
{
FloorId = F0001;
endCoordinates = "NSPoint: {541, 413}";
linePath = "<UIBezierPath: 0x1d0903c0>";
pointsOnLine = (
);
startCoordinates = "NSPoint: {418, 504}";
},
To write to the Core Data I use following code: parray is type BinaryData
points.parray = [NSKeyedArchiver archivedDataWithRootObject:self.locationsArray];
and to retrieve value I use
locationsArray = [NSKeyedUnarchiver unarchiveObjectWithData:points.parray];
When I try to retrieve it i get following error :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSDictionary initWithObjects:forKeys:]: count of objects (0) differs from count of keys (5)'
I have checked that NSArray and NSDictionary adopts NSCoding protocol. What am I doing wrong here ?
The best way to solve this is to create either a small test app, or a test method called when your app launches. Create a typical dictionary using the same keys and types, try to archive it, log the data size, then immediately try to unarchive the data. Assuming it fails comment out one or more keys til what's left works. Now you know the problem key and can better determine what is wrong.
Related
My iOS app terminates with Thread 1: signal SIGABRT error. The strange thing is, when I hover the cursor over the NSNumber object (where the error has occurred), it displays the objects of an NSDictionary with Key/Value pair. Following is my code snippet:
for(id obj in [MainDict allKeys])
{
NSArray *AnArrayInsideMainDict = [MainDict objectForKey:obj];
double i=1;
for(NSUInteger n=0; n<4; n++)
{
NSNumber *anObject = [AnArrayInsideMainDict objectAtIndex:n];
NSNumber *nextObject = [nextDict objectForKey:[NSNumber numberWithDouble:i]];
NSNumber *HereIsTheError = [NSNumber numberWithFloat:(powf(([anObject floatValue]-[nextObject floatValue]),2))];
[ThisIsMutableArray addObject:HereIsTheError];
i++
}
}
Here, the MainDict contains 64 key/value pairs (each key contains an NSArray of 5 objects).nextDictis an NSDictionary with 4 key/value pairs (each key contains one NSNumber object // EDIT: each key actually contained an NSArray with single NSNumber Object, this was the reason for the error). After the app termination and hovering the cursor over the HereIsTheError, I get following key/value pair:
The terminating error at the console is:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM floatValue]: unrecognized selector sent to instance 0x170257a30'
*** First throw call stack:
(0x18b032fe0 0x189a94538 0x18b039ef4 0x18b036f54 0x18af32d4c 0x1000891a0 0x10008bd74 0x10020d598 0x100579a50 0x100579a10 0x10057eb78 0x18afe10c8 0x18afdece4 0x18af0eda4 0x18c979074 0x1911c9c9c 0x1000906b4 0x189f1d59c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
How can NSNumber conation the objects of NSDictionary? I use Xcode Version 9.0.1 (9A1004) and Objective-C.
As the comments state, but most importantly your error message states, your objects anObject and nextObject are not NSNumber's - they are NSMutableArray's, hence the
-[__NSArrayM floatValue]: unrecognized selector...
part of your error.
Ensure the objects in AnArrayInsideMainDict are in fact
NSNumber's before attempting to cast them as numbers,
I would suggest flagging your objects before "assuming" their types, but I doubt that would help you get your desired outcome (as this would most likely from your case here skip each object that is not an NSNumber).
Before you even enter the for loop in [MainDict allKeys], backtrace to make sure you are in fact passing arrays of NSNumber's as the dictionaries objects.
IF you are actually not sure of the object types, you can just throw a flag to make sure you are not misinterpreting any of the objects:
...
for (NSUInteger n=0; n<4; n++) {
NSNumber *anObject = [AnArrayInsideMainDict objectAtIndex:n];
NSNumber *nextObject = [nextDict objectForKey:[NSNumber numberWithDouble:i]];
if ([anObject isKindOfClass:NSNumber.class] && [nextObject isKindOfClass:NSNumber.class]) {
// Good to continue now that you know the objects
} else NSLog(#"whoops.. anObject: %# nextObject: %#", anObject.class, nextObject.class);
...
LASTLY, if you are so daring, and are sure that somewhere in this dictionary are your NSNumber's, you could flag your steps to check for instances of the NSNumber.class in order to seek out your floats.
Otherwise, I suggest deep diving into the how and where you are getting your MainDict from.
Happy coding - cheers!
I have a NSMuttableArraywhich contains the structure like below,
28 = (
twenty
);
30 = (
thirty
);
32 = (
thirty
);
I am trying to store the values like 28,30,32 into a separate array. I tried loop as,
NSMutableArray *getvalueshere;
for(int i=0;i<getvalueshere.count;i++)
NSArray *getval = [getvalueshere objectAtindex:i];
}
On trying this, my app gets crash saying __NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance.
Your object is a NSDictionary as the error message reveals.
You can get the numbers – which are actually the keys of the dictionary – with
NSArray *getval = [getvalueshere allKeys];
It's saying getvalueshere is an NSDictionary which doesn't recognize objectAtIndex. When you declared getvalueshere, you gave it a NSDictionary like structure. It is considered an NSDictionary even though you explicitly stated it should be an NSMutableArray.
I created my own dictionary by taking the values from a json file in the dictionary I have a set of values, the other can take them and use them, instead of these start with a brace can not seem to get them:
weather = (
{
description = "broken clouds";
icon = 04d;
id = 803;
main = Clouds;
}
);
Use this command to take the values in the Dictionary:
NSString *currweather = myDict[#"weather"][#"main"];
The application quits when the launch. How can I fix?
NSString *currweather = myDict[#"weather"][0][#"main"];
The weather key is referencing an array of dictionary.
You should have been given a clue from the error message about an unrecognized selector (objectForKey:) being called on an array class.
Basically I'm working on an app to allow users to track their tv shows. A user can click their tv show to get a season and episode breakdown.
To achieve this, I am trying to gather JSON data from this API, and then store the data into core data.
The API call is this:
http://api.trakt.tv/show/summary.json/36590b30dc7d0db9ebd3153b1a989e5d/arrow/1
I can successfully store the values of: title, year, url, first_aired etc. But I can't work out how to store the season and episode information into my core data (located about half way down the JSON API call)
I have included a link to a screenshot of how I've set out my core data model:
!http://i546.photobucket.com/albums/hh427/camcham/ScreenShot2013-10-17at34449AM.png
The code below is how I'm currently trying to store the JSON data into my core data (using MagicalRecords)
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
Show *showp = [Show MR_findFirstByAttribute:#"sID" withValue:showID inContext:localContext];
if (![showp.sID isEqualToString:showID])
{
//Create New Show in current thread
Show *showContext = [Show MR_createInContext:localContext];
showContext.title = showTitle;
showContext.poster = showPoster;
showContext.year = showYear;
showContext.sID = showID;
//code above this comment correctly adds right JSON info to core data and i can access and display it properly
The next part of my code I have tried to convert an NSArray to NSSet, as my 'seasons' relationship is of type NSSet, however I believe the JSON data is NSArray. I am getting the following error: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber managedObjectContext]: unrecognized selector sent to instance 0xa22a680'
NSArray *show = [(NSSet *)[JSONEvents objectForKey:#"seasons"] valueForKey:#"season"];
showContext.seasons = [NSSet setWithArray:show];
The code below does not work as intended. episode.title for example, stores every single episode's title, instead of just the single title for a particular episode.
Season *season = [Season MR_createInContext:localContext];
season.seasonNumber = [(NSDictionary *)[JSONEvents objectForKey:#"seasons"] valueForKey:#"season"];
season.episodes = [(NSDictionary *)[JSONEvents objectForKey:#"seasons"] valueForKey:#"episodes"];
Episode *episode = [Episode MR_createInContext:localContext];
episode.title = [[(NSDictionary *)[season.episodes objectForKey:#"seasons"] valueForKey:#"episodes"] valueForKey:#"title"];
episode.overview = [[(NSDictionary *)[JSONEvents objectForKey:#"seasons"] valueForKey:#"episodes"] valueForKey:#"overview"];
So to sum it all up, I would love for someone to demonstrate the correct way to store the tv seasons and episodes from my JSON API, so I can then utilise this data in my app!
Removing the cast to (NSSet *) should fix the error.
NSArray *show = [[JSONEvents objectForKey:#"seasons"] valueForKey:#"season"];
showContext.seasons = [NSSet setWithArray:show];
instead of
NSArray *show = [(NSSet *)[JSONEvents objectForKey:#"seasons"] valueForKey:#"season"];
showContext.seasons = [NSSet setWithArray:show];
I am grabbing images from the users' contacts in their iOS Address Book/Contacts.app. And putting them in a dictionary to upload as JSON.
I am getting the following error:
2012-12-05 10:38:01.286 ContactsApp[6247:713f] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSCFData)'
*** First throw call stack:
(0x2de6012 0x286ce7e 0x2de5deb 0x20926fe 0x2096b21 0x2dd3cdf 0x2dd387d 0x2dd37c5 0x20966fa 0x209262d 0x2096b21 0x2dd3cdf 0x2dd387d 0x2dd37c5 0x20966fa 0x209262d 0x20969af 0x2ddfe7c 0x2ddfa16 0x2ddf925 0x20968b8 0x2092679 0x2096b21 0x2dd3cdf 0x2dd387d 0x2dd37c5 0x20966fa 0x209262d 0x20923bd 0x209579c 0x1cad5 0x67475 0x66a87 0x14399cd 0x746008f 0x3dc253f 0x3dd4014 0x3dc52e8 0x3dc5450 0x90e36e12 0x90e1ecca)
libc++abi.dylib: terminate called throwing an exception
I've using the following code:
if (ABPersonHasImageData(addressBookContact)) {
NSMutableDictionary *imageDictionary = [NSMutableDictionary dictionary];
NSData *thumbnailImageData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(addressBookContact, kABPersonImageFormatThumbnail);
NSData *originalImageData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(addressBookContact, kABPersonImageFormatOriginalSize);
if (thumbnailImageData) [imageDictionary setObject:thumbnailImageData forKey:#"thumbnailImage"];
if (originalImageData) [imageDictionary setObject:originalImageData forKey:#"originalImage"];
[contactDictionary setObject:imageDictionary forKey:#"image"];
}
The error occurs when I am trying to place the array into this request:
[addressBookArray addObject:contactDictionary];
if ([addressBookArray count] % 15 == 0) {
// I'm using AFNetworking
[[APIClient sharedClient] requestWithMethod:#"POST" path:#"cmd/addContact" parameters:#{ #"addressBookEntries" : addressBookArray }];
[addressBookArray removeAllObjects];
}
Your problem is that you are attempting to put NSData objects into a JSON object. Instead of adding the image data to the imageDictionary, add the base64 encoding of the images to the imageDictionary and you should have no problem.
Matt Gallagher has a handy class for handling base64 here: http://www.cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
Looks like AFNetworking is trying to parse your parameters into JSON, but you're passing it an NSData. Although your passing it an NSDictionary, which is valid, those nested types need to be either other NSDictionaries, NSArrays, NSStrings, and NSNumbers. If you want to append image NSDatas, you have to use a different content-type and append the image data.