NSArray valueForKey:#"#max.self"? - ios

I have an Array of numbers in which I want to find the highest value.
I am doing this as follows:
NSNumber *test = [fuelConsumption valueForKey:#"#max.self"];
When I Build then Run, I am presented with the following error:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSArrayM 0x7b26e8d0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key max.self.'
From what I understand, this is how one looks for this value.
Any ideas where this may be going wrong?
I am programming for iOS9.x and using Xcode 7.3.1

You are getting exception because, when you give valueForKey: an NSString, it will invoke objectForKey: and when string starts with an # it invokes [super valueForKey:], which may call valueForUndefinedKey: which may raise an exception.
So, change valueForKey: to valueForKeyPath: like,
NSNumber *test = [fuelConsumption valueForKeyPath:#"#max.self"];
Read more about kvc-collection-operators.

You need to use valueForKeyPath for that
NSNumber *test = [fuelConsumption valueForKeyPath:#"#max.self"];
For more about Collection Operators read apple documentation.

Related

Sort NSMutableArray using NSSortDescriptor

I'm building an iOS app. I need to sort an NSMutableArray, so I used NSSortDescriptor. However, when I run my app, I unfortunately get Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSTaggedPointerString 0xa000000343730314> valueForUndefinedKey:]: this class is not key value coding-compliant for the key ID.'.
This is the code I'm using:
customerArray = [[NSMutableArray alloc] initWithArray:[rootDict allKeys]];
NSSortDescriptor *numberSorter = [NSSortDescriptor sortDescriptorWithKey:#"ID" ascending:YES selector:#selector(localizedStandardCompare:)];
[customerArray sortUsingDescriptors:#[numberSorter]];
Before, when I was just using customerArray = [[NSMutableArray alloc] initWithArray:[rootDict allKeys]];, I had no issues. Once I added the other two lines, I started having problems. I checked where it crashes using breakpoints, and found that it crashes after trying to run the last line ([customerArray sortUsingDescriptors:#[numberSorter]];).
Any help would be appreciated, and I will gladly add more code if needed.
As your error states valueForUndefinedKey which means that the objects inside the NSMutableArray i.e. customerArray in your case does not have a key with name ID (Undefined Key).
You need to check the objects inside your NSMutableArray.
Hope this solves your problem.

Changing integer values in NSMutableArray, IOS Objective-C

I created an array that would hold some integers. However I seem to get an error on a line of code which is trying to alter one of the values in the array. I have created an array as follows:
NSMutableArray *lockedArray;
lockedArray = [NSMutableArray arrayWithCapacity:50];
I have added some values into the array:
[lockedArray addObject:#10];
[lockedArray addObject:#20];
[lockedArray addObject:#30];
[lockedArray addObject:#40];
[lockedArray addObject:#50];
[lockedArray addObject:#60];
[lockedArray addObject:#70];
[lockedArray addObject:#80];
Now I want to change one of the values. For example if I want to change the 6th value then I use the following code...
[lockedArray replaceObjectAtIndex:5 withObject:#1];
In Xcode I do not get any warning and it all looks fine. When I run the code and initiate replacing an object it crashes and gives me the following error...
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: '-[__NSCFArray
replaceObjectAtIndex:withObject:]: mutating method sent to immutable
object'
We don't know what you are doing exactly, but at the point where replaceObjectAtIndex is called, lockedArray is not a mutable array but an immutable array.
Since an array cannot be changed from being mutable to immutable, you most likely assigned a different (immutable) array to lockedArray after you added the other elements.
Have u allocated and initialized ur array like this,
lockedArray = [[NSMutableArray alloc]init];
Try it, Hope it will work for u
Make sure you check that you haven't pointed lockedArray to a non mutable array or you haven't initiated it as such. Use Xcode's find function to search for
"lockedArray = [NSArray"
or
"lockedArray ="

Unable to append String NSMutableString - Error

I have the following code
NSMutableString *ibmcountryCodeLabel=[[NSMutableString alloc]init];
NSMutableString *imobileNumberValue=[[NSMutableString alloc]init];
ibmcountryCodeLabel=#"555";
imobileNumberValue=#"333";
NSLog(#"Done1");
[ibmcountryCodeLabel appendString:imobileNumberValue];
NSLog(#"Done2");
Though both the string are mutable when I try to append one with another I am getting "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendString:'"
read through all the threads. But not able to find a solution. Kindly help me. Thanks for your time
Here is the problem: this assignment produces a mutable string object:
NSMutableString *ibmcountryCodeLabel=[[NSMutableString alloc]init];
After this assignment, however, the object pointed to by ibmcountryCodeLabel is no longer mutable:
ibmcountryCodeLabel=#"555";
This is because the #"555" constant is an immutable subclass of NSString. Trying to modify it leads to runtime errors.
Change the code as follows to fix this problem:
NSMutableString *ibmcountryCodeLabel=[NSMutableString stringWithString:#"555"];
NSMutableString *imobileNumberValue=[NSMutableString stringWithString:#"333"];

How to resolve a NULL cString crash

I'm getting a crash with the following encoding fix I'm trying to implement:
// encoding fix
NSString *correctStringTitle = [NSString stringWithCString:[[item objectForKey:#"main_tag"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
cell.titleLabel.text = [correctStringTitle capitalizedString];
my crash log output states:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSString stringWithCString:encoding:]: NULL cString'
thanks for any help
You seem to think that a double conversion is necessary in order to get the correct result. It isn't, nor is it possible (that's why the call to cStringUsingEncoding:NSISOLatin1StringEncoding returns NULL). Just leave this part out and assign to correctStringTitle directly.
I had the same problem with italian accented characters while trying to get text from html and my solution to avoid the situation that cStringUsingEncoding:NSISOLatin1StringEncoding returns NULL is ensuring that when you get the html from data you use:
[[NSString alloc] initWithData:self.responseData encoding:NSISOLatin1StringEncoding]
and not
encoding:NSUTF8StringEncoding

append a NSString converted from dictionary object to NSMutableArray

I have been bothered by this problem for a long time.
I have a NSString which is the received from a RSS parser, I can successfully NSlog it on the screen, but when I try to append it to an existing NSmutablearray, it causes exception.
Here is my code.
//mystring is a NSMutableString with some content initialized succesfully
NSString *myDate = [dic objectForKey:#"date"];
NSLog(#"%# and %#",myString,myDate);
[myString appendString:myDate];
until the NSLog, both myDate and myString are printed on screen correctly as I desire, but the appendString line causes error
[_NSDate length]: unrecognized selector sent to instance 0*7141a00
Terminating app due to uncaught exception 'NSInvalidArgumentException', reasons: '-[__NSDate length]: ..........
Could someone please help me?
You're calling -appendString: with myDate, which isn't a string. It's an NSDate. You can't pass it to an API that expects a string. You need to convert it into a string somehow. This is probably best done using NSDateFormatter, which gives you full control over how to format your date as a string.
For testing purposes though, you can just replace your last line with [myString appendString:[myDate description]] and it should stop crashing.

Resources