nsdictionary issue - objective-c

I have the following data in a NSDictionary Variable:
{
value = "TV-PG";
}
I was wondering how to get the value for key "value" here.
I tried:
NSDictionary *fieldMaturityRating = [[parsedItems objectAtIndex:0] objectForKey:#"field_maturity_rating"];
NSString *dateRelease = [fieldMaturityRating objectForKey:#"value"];
(where, fieldMaturityRating is a NSDictionary with the given value)
and I get:
-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0xd9cd3f0
[10530:707] *** Terminating app due to uncaught exception: -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0xd9cd3f0
Can anyone kindly help me ?
Thanks.
Note: if I pause the execution and do a po after the 1st line of code presented here, I get the following:
(gdb) po fieldMaturityRatingNew
<__NSArrayM 0x79af250>(
{
value = "TV-PG";
}
)

The po actually shows your issue:
(gdb) po fieldMaturityRatingNew
<__NSArrayM 0x79af250>(
{
value = "TV-PG";
}
)
The outer ( and ) mean that your object is actually an array.
Inside that is where the { and } denote your dictionary.
So you really want:
NSString *value = [[fieldMaturityRatingNew objectAtIndex:0] objectForKey:#"value"];

You're actually sending that NSDictionary message to a NSMutableArray instance.
You might want to check your code again as the objectForKey: method is right when pointing to a NSDictionary.

This means your fieldMaturityRating is not actually an NSDictionary. Make sure you aren't setting it to an array somewhere in your code.
Edit:
This means your fieldMaturityRating is actually an NSArray containing an NSDictionary. If this is your intended data structure then you can access your value like so.
NSString *dateRelease = [[fieldMaturityRating objectAtIndex:0] objectForKey:#"value"];
I don't believe this is your intended data structure so you should look into why your parsedItems array returned you an NSArray instead of an NSDictionary. If you track this problem down you can stop any headaches in the future.

Based on your datastructure which is a dictionary inside an array, dateRelease should be like this
NSString *dateRelease = fieldMaturityRating[0][#"value"];

Related

Error trying to separate an array containing managed object context

Could anyone please tell me why I am getting this error and why this code isn't working?
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSArrayI componentsSeparatedByString:]: unrecognized
selector sent to instance 0x109494750'
This is the code with problems:
NSArray *array = [self.managedObjectContext executeFetchRequest:request error:nil];
NSString *dateString = [array valueForKey:#"dateString"];
NSArray *datesArray = [dateString componentsSeparatedByString:#","];//line with problems
When you call valueForKey: on array the result will be an NSArray containing the result of calling valueForKey: on each of it's elements.
So dateString is not actually a string it's an instance of NSArray, which does not respond to componentsSeparatedByString:. You need to index into the array to get the date you want before calling componentsSeparatedByString: on that
It's an indication that dateString isn't a string. When you call -valueForKey: on an array, it returns an array. Per the docs:
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.
So you're calling a string method on an array. It's not clear what you're trying to accomplish by calling -valueForKey:. Perhaps you meant -objectAtIndex:?

Invalid Selector on doubleValue

A bit new to Objective-C, so please bear with me.
Firstly, I'm using the FMDB library for SQLite management.
I'm populating an NSMutableDictionary using the following method:
//....
while([effectivenessResults next]) //this loops through the results of a query (verified that this works)
{
NSMutableArray *dFactors = [[NSMutableArray alloc]init];
if([resultDict objectForKey:[effectivenessResults stringForColumn:#"tName"]])
{
dFactors = [resultDict objectForKey:[effectivenessResults stringForColumn:#"tName"]];
}
NSNumber *effectivenessValToAdd = [NSNumber numberWithDouble:[effectivenessResults doubleForColumn:#"dFactor"]/100];
[dFactors addObject:[NSMutableString stringWithFormat:#"%#",effectivenessValToAdd]];
[resultDict setObject:dFactors forKey:[effectivenessResults stringForColumn:#"tName"]];
}
I'm returning the array properly (I have verified this). Then, I am accessing this NSMutableDictionary elsewhere, using the follwing method:
for(id type in tEffect) //tEffect is the NSMutableDictionary, returned from the previous code (there known as resultDict)
{
effectivenessString = [self getEffectivenessString:[tEffect objectForKey:type]];
tInfo = [NSMutableString stringWithFormat:#"%#", [tInfo stringByAppendingFormat:#"%#: %#\n", type, effectivenessString]];
}
which calls the following two methods:
-(NSMutableString *)getEffectivenessString:(NSNumber *) numberPassedIn
{
double dFactor = [numberPassedIn doubleValue];
//adds the above value to a string, this will not affect anything
}
and
-(NSNumber *) listProduct: (NSMutableArray *)listOfValues //calculates the product of an NSMutableArray of numbers
{
NSNumber *product=[NSNumber numberWithDouble:1.0];
for(int i = 0; i < [listOfValues count]; i++)
{
NSNumber *newVal = [listOfValues objectAtIndex:i];
product = [NSNumber numberWithDouble:[product doubleValue] * [newVal doubleValue]];
}
return product;
}
So, when I call these methods, I am getting the following error:
2013-08-04 13:52:04.514 effectCalculator[45573:c07] -[__NSArrayM doubleValue]:
unrecognized selector sent to instance 0x8c19e00
2013-08-04 13:52:04.521 effectCalculator[45573:c07] *** Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: '-[__NSArrayM doubleValue]: unrecognized
selector sent to instance 0x8c19e00'
Important to note: This error occurs on the retrieval, NOT the populating of the NSMutableDictionary. This means the population of this dictionary not the an issue, but it might have something to do with why it's having trouble retrieving the data.
So what might cause this error?
Your code is pretty difficult to follow. In future please post a minimal sample which compiles, or at least is a single block of understandable code.
Having said that, I believe your issue is with this bit:
for(id type in tEffect) //tEffect is the NSMutableDictionary, returned from the previous code (there known as resultDict)
{
effectivenessString = [self getEffectivenessString:[tEffect objectForKey:type]];
what does resultDict contain?
[resultDict setObject:dFactors ...
but dFactors is an NSMutableArray. Well getEffectivenessString expects a NSNumber, not a NSMutableArray. So it complains. Also I think you intended for the method to take a string, not a number, although I don't see why you're not casting as you load them (instead of as you use them).
Since Objective C doesn't support strongly-typed arrays or dictionaries, your best bet to defend against this in the future is to name your variables more logically. It should stand out when you try to call a method which expects a number with an array instead.

-[NSNull objectForKeyedSubscript:]: unrecognized selector sent to instance

I got an exception that says:
-[NSNull objectForKeyedSubscript:]: unrecognized selector sent to instance
Is it saying I am trying to access an NSNull object with a key?
Any idea what causes this and how to fix it or debug further?
The way to fix it is to not attempt objectForKeyedSubscript on an NSNull object. (I'm betting you're handling some JSON data and aren't prepared for a NULL value.)
(And apparently objectForKeyedSubscript is what the new array[x] notation translates into.)
(Note that you can test for NSNull by simply comparing with == to [NSNull null], since there's one and only one NSNull object in the app.)
What ever value you are storing, despite what the editor tells you, at run time you are storing an NSNull, and later on trying to call objectForKeyedSubscript. I am guessing this happening on what is expected to be an NSDictionary. Some thing like:
NSString *str = dict[#"SomeKey"]
Either a piece of code beforehand is not doing its job and investigate there, or perform some validation:
NSDictionary *dict = ...;
if ( [dict isKindOfClass:[NSDictionary class]] ) {
// handle the dictionary
}
else {
// some kind of error, handle appropriately
}
I often have this kind of scenario when dealing with error messages from networking operations.
I suggest adding a category to NSNull to handle this in the same way you would expect a subscript call to be handled if it it were sent to nil.
#implementation NSNull (Additions)
- (NSObject*)objectForKeyedSubscript:(id<NSCopying>)key {
return nil;
}
- (NSObject*)objectAtIndexedSubscript:(NSUInteger)idx {
return nil;
}
#end
A simple way to test is like this:
id n = [NSNull null];
n[#""];
n[0];
With this category, this test should be handled successfully/softly.

Why am I getting this: _cfurl: unrecognized selector

My init starts like this:
- (id) init {
[super init];
sounds = makeDictFromArrayOfURLs(getNoiseFileURLs());
[sounds retain];
NSURL *theFirstNoise = [[sounds allKeys] objectAtIndex:0];
CFURLRef uref = (CFURLRef)theFirstNoise;
OSStatus ret = AudioServicesCreateSystemSoundID(uref, &chosenNoise);
When we get to that last line, it throws this:
2011-06-09 23:19:18.744 SuperTimer[94516:207] -[NSPathStore2 _cfurl]: unrecognized selector sent to instance 0x940cfb0
2011-06-09 23:19:18.746 SuperTimer[94516:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSPathStore2 _cfurl]: unrecognized selector sent to instance 0x940cfb0'
Yeah, it's a bit uncompact for debugging.
Just before I get the dump, theFirstNoise contains the expected (sort of) data. (It's description method prints a weird form, but I am informed that's normal.)
Off the top of my head, it looks like theFirstNoise is actually an NSPathStore2 (a private subclass of NSString) instead of an NSURL.
Edit: NSPathStore2 objects will contain file paths. If you need to turn these into NSURLs, you can simply pass them to +[NSURL fileURLWithPath:].
This line:
NSURL *theFirstNoise = [[sounds allKeys] objectAtIndex:0];
is the problem: [sounds allKeys] returns an NSArray of keys, and objectAtIndex: therefore is returning an NSString, and not the URL. I wish the compiler would have been a little more helpful.

Unrecognized Selector Sent to Instance [NSCFString subarrayWithRange:]

I have the following code which is producing this error. I cannot understand why the subarrayWithRange message is being sent to a string? When it is clearly an array?
static const int kItemsPerView = 20;
NSRange rangeForView = NSMakeRange( page * kItemsPerView, kItemsPerView );
NSMutableArray *temp = [[APP_DELEGATE keysArray] mutableCopyWithZone:NULL];
NSArray *itemsForView = [temp subarrayWithRange:rangeForView];
for (int loopCounter = 0;loopCounter < r*c;loopCounter++){
NSLog(#"%i: %# ", loopCounter, [itemsForView objectAtIndex:loopCounter]);
}
Error:
-[NSCFString subarrayWithRange:]: unrecognized selector sent to instance 0x6b071a0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: [NSCFString subarrayWithRange:]:
Thanks
These kinds of errors are usually memory-management-related. Essentially, you're sending a message to an address that's now occupied by some other object because the previous occupant has unexpectedly disappeared. Since that address space could be occupied by anything, you just happen to be asking an NSCFString something to which it doesn't respond.
If you pause the debugger right after you create the temp array, what do you see assigned to temp? I'm guessing something's not quite right with whatever -keysArray returns. You might want to double-check how the memory is handled in whatever that's supposed to return. By the name, I suppose your app delegate has an array called "keysArray" as an instance variable. Perhaps that's not being properly retained when it's created or assigned?
So I had this one. I did something stupid. I assigned the UITextView to a string instead of it's text property. ie:
myObj.txtbxThing = [NSString stringWithFormat:#"%#", stuffString];
instead of:
myObj.txtbxThing.text = [NSString stringWithFormat:#"%#", stuffString];