How To convert [__NSArrayI integerValue] to integer value? - ios

This the line i have using to convert the object to integer values,Inside For Loop I have Placed This code
NSInteger tag=[[arrFullSubCategory valueForKey:#"category"] integerValue];
Inside arrFullSubCategory:
(
{
category = 35;
image = "images/Hatchback.jpg";
name = Hatchback;
parent = 20;
},
{
category = 36;
image = "images/Sedan.jpg";
name = Sedan;
parent = 20;
},
{
category = 37;
image = "images/SUV.jpg";
name = SUV;
parent = 20;
}
)
Exception:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI integerValue]: unrecognized selector sent to instance 0x7ff4ba58f930'

arrFullSubCategory is an array and you should reach it's elements first. Than you will have NSDictionary objects. After that you can access your category element. So I think your code should be like that:
for (NSInteger i = 0; i < arrFullSubCategory.count; ++i) {
NSInteger tag=[[[arrFullSubCategory objectAtIndex:i] valueForKey:#"category"] integerValue];
}

Explanation of the error:
The error means you have an array, and arrays don't respond to integerValue.
Your variable arrFullSubCategory references an array (of 3 elements), and each element is a dictionary. If you call valueForKey: on an array of dictionaries then the key lookup is performed for each dictionary and an array is constructed for the results. In your case the result (using literal syntax) is the array:
#[ #35, #36, #37 ]
Whether this array is directly useful to you, or whether you should access the array one element at a time - using a loop or method which calls a block per element, etc. - will depend on what your goal is.
HTH

Try this code inside for loop I hope this help you
NSInteger tag=[[[arrFullSubCategory objectAtIndex:i] valueForKey:#"category"] integerValue];

you have array of dictionary, So you use it given below code
[[[arrFullSubCategory objectAtIndex:] objectForKey:#"category"] integerValue]

Related

NSNumber storing objects of NSDictionary in Objective-C

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!

__NSCFDictionary doesn't respond to any selectors

I am trying to Parse JSON that looks like this:
food = {
"food_id" = 4823;
servings = {
serving = (
{
calcium = 9;
calories = 221;
carbohydrate = "16.20";
cholesterol = 31;
I can successfully retrieve the array at the [food][servings][serving] level, which I confirm via a log statement has the appropriate class, __NSCFArray, but I run into a problem when iterating through that array and trying to do useful things with the contained information:
for (id foodId in resultsPerServing) {
NSLog(#"hree is a result %#", foodId);
foodObjectClass *foodObject = [foodObjectClass new];
NSDictionary *foodIdDictionary = (NSDictionary *)foodId;
if ([foodIdDictionary respondsToSelector:#selector(allKeys)]) {
[foodObject getDetailsFromResponseObject:foodIdDictionary];
} else {
unsigned int mc = 0;
Method * mlist = class_copyMethodList(object_getClass(foodIdDictionary), &mc);
NSLog(#"%d methods", mc);
for(int i=0;i<mc;i++)
NSLog(#"Method no #%d: %s", i, sel_getName(method_getName(mlist[i])));
[NSException raise:#"DIDN'T GET A DICTIONARY" format:#"here is the object %# which has class %#", resultsPerServing, [responseObject class]];
}
}
This causes the NSException to be raised without fail although in the NSException the output from printing the object looks like a dictionary. Additionally, when the exception prints out the class of the object which does not respond to allKeys, that object has class __NSCFDictionary. What gives? Why does this dictionary not have an allKeys method and how can I get a functional dictionary to work with?
Even more puzzling is that the runtime code below (copied from an SO post for which I have lost the link) indicates that the dictionary has 0 methods. Why does this object have no methods? How can I get an object that does have methods?
make a check to confirm that it as NSDictionary first?
if ([foodId isKindOfClass:[NSDictionary class]] ) {
foodIdDictionary = (NSDictionary *)foodId;
[foodObject getDetailsFromResponseObject:foodIdDictionary];
}

Shopify iOS SDK - issue converting BuyProductVariant to BuyProduct

I am having an issue converting a BuyProductVariant to BuyProduct, as from BuyCart i am getting the array of all the Variants which are added in that cart with the following code
NSArray *arr = cart.lineItems;
Now as per my understanding, this array contains all the Variants which are added in the Cart.
After that I am getting those object in BuyProductVariant
for (int j=0; j<arr.count; j++) {
BUYProductVariant *variant = arr[j];
//As the product is defined in BuyProductVariant class
BUYProduct *product = variant.product;
//But when the above line executes the app crashes, below is the description
}
exception: -[__NSDictionaryM product]: unrecognized selector sent to instance 0x7fd3286d3c50
Now, in the above code, where am i doing the wrong, any help would be very helpful to me.
Thanks
the BUYCart.lineItems array does not contain BUYProductVariant object. It contains BUYCartLineItem objects. You can retrieve your BUYProductVariant from it.
for (BUYCartLineItem* line in cart.lineItems) {
BUYProductVariant* productVariant = line.variant;
}

Error while parsing NSMutablearray values

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.

Saving an NSMutableDictionary to NSUserDefaults

In my application one of the things I am saving is the value of a group of switches. The idea is to save the state of each switch in an NSMutableDictionary. In another method I read out the value ("state") of each switch and use that to perform a simple calculation. These switches tell me what the user has, basically.
In my data model.
-(void)savePlates:(NSMutableDictionary *)settingPlates {
[self setObject:settingPlates forKey:#"plates"];
[self synchronize];
}
-(NSMutableArray *)loadPlates {
NSMutableArray *plates = [[self dictionaryForKey:#"plates"] mutableCopy];
return plates;
}
An example of using this in the View Controller. Where 'settings' is an instance of the class that defines the methods above.
-(IBAction)switch55:(id)sender {
if (self.switch55.on) {
[self.plateSelectionDict setObject:#YES forKey:#55];
} else {
[self.plateSelectionDict setObject:#NO forKey:#55];
}
[settings savePlates:self.plateSelectionDict];
if (DEBUG) {
NSLog(#"%#", self.plateSelectionDict);
}
}
I am crashing on this line.
[self setObject:settingPlates forKey:#"plates"];
The error is,
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
'*** -[Settings setObject:forKey:]: attempt to insert non-property list object {
55 = 0;
25 = 1;
"0.25" = 1;
"0.5" = 1;
"0.75" = 1;
45 = 1;
15 = 0;
1 = 1;
10 = 1;
"2.5" = 1;
35 = 1;
5 = 1;
} for key plates'
What is confusing is that it is spitting out the correct values, but still throwing an exception. I must be doing something terribly wrong. Any assistance would be appreciated.
All keys must be strings if you need to save it to NSUserDefaults or a plist. Your keys are numbers.
To save objects to user defaults , your objects need to be valid property list objects.
If you want to check which objects are valid property list objects, just create a new plist file and play for a while with it , add some entries and you'll see what types are already handled / available to be saved without any previous preprocessing to read/write them.
At first glance it seems your values are booleans and string / nsnumbers keys, which are valid.
I'd suggest printing out the class of the objects and checking if all them are actually valid.
You can get more information here
https://developer.apple.com/library/ios/documentation/cocoa/conceptual/PropertyLists/Introduction/Introduction.html

Resources