Sort NSMutableArray using NSSortDescriptor - ios

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.

Related

NSArray valueForKey:#"#max.self"?

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.

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"];

ios unrecognized selector [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
-[__NSCFDictionary JSONRepresentation]: unrecognized selector sent to instance
I use SBJson ( http://stig.github.com/json-framework/ ) in two of my project. Therefore I downloaded the code and copied it into my first project so that I can do something like this
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setValue:email forKey:#"email"];
[dict setValue:password forKey:#"password"];
NSString* json = [dict JSONRepresentation];
Now for my second and new project I did the same. I copied all the source files from SBJson into my new project and used the exact same code as above. But now when the program comes to line NSString* json = [dict JSONRepresentation]; I get the following error message:
-[__NSCFDictionary JSONRepresentation]: unrecognized selector sent to instance 0x689c710
What am I doing wrong in my second project?
Make sure that all the files have been added to the target.
Since iOS 5 you don't need an external library to use JSON, This tutorial could help you with that.
That error is because you are telling to dict, which is an instance of NSMutableDictionary, to perform a method called JSONRepresentation. dict doesn't know how to do that. I haven't work with that library but I would guess that you need to make an instance of SBJSON parser and then send dict as parameter. I found this and this tutorials, I hope they can help you.

Managed Object Method Error "unrecognized selector sent to instance"

In the process of teaching myself objective C and the iOS SDK. I've gotten to a point where I think I understand what I'm doing yet I'm hitting a roadblock that I don't see a way past. I've created a core data model with multiple entities, with one master entity having a couple many to one relationships with a couple other entities. And I'm able to work with the main entity just fine, as well as any object that are on a one to one relationship with the main entity. However, when I try to add an entity to one of the NS Set based entities using the core data generated accessors, I am getting an unrecognized selector error: Here's some code to confuse things even more:
Weapon *tempWeapon = [NSEntityDescription insertNewObjectForEntityForName:#"Weapon" inManagedObjectContext:inputContext];
NSArray *tempWeaponStats = [inputMech getMechWeaponStats:tempEquipName];
tempWeapon.weaponName = tempEquipName;
tempWeapon.weaponDisplayName = tempEquipDisplayName;
tempWeapon.weaponLocation = tempEquipLocation;
tempWeapon.weaponType = tempEquipType;
tempWeapon.weaponCritSize = tempEquipSize;
tempWeapon.weaponHeat = [[NSNumber alloc] initWithInt:[[tempWeaponStats objectAtIndex:0] intValue]];
tempWeapon.weaponDamage = [[NSNumber alloc] initWithInt:[[tempWeaponStats objectAtIndex:1] intValue]];
tempWeapon.weaponRangeMin = [[NSNumber alloc] initWithInt:[[tempWeaponStats objectAtIndex:2] intValue]];
tempWeapon.weaponRangeShort = [[NSNumber alloc] initWithInt:[[tempWeaponStats objectAtIndex:3] intValue]];
tempWeapon.weaponRangeMed = [[NSNumber alloc] initWithInt:[[tempWeaponStats objectAtIndex:4] intValue]];
tempWeapon.weaponRangeLong = [[NSNumber alloc] initWithInt:[[tempWeaponStats objectAtIndex:5] intValue]];
NSLog(#"Adding to the weapon list %#", tempWeapon.weaponName);
[inputMech insertObject:tempWeapon inWeaponListAtIndex:(NSUInteger)0];
When running this code, I get the following error:
2011-08-24 01:49:52.643 DigitalRecordSheet[12947:f203] -[Mech insertObject:inWeaponListAtIndex:]: unrecognized selector sent to instance 0x718bbe0
Now, inputMech is of the master entity type I mentioned earlier. Here's the core data generated selector from Mech.h:
(void)insertObject:(Equipment *)value inEquipmentListAtIndex:(NSUInteger)idx;
As far as I can tell, I am sending the message properly, but it doesn't work. Basically, I want to have one Mech that has a list of multiple weapons. Now, am I wrong in how I am doing this? I am assuming that I have to create a new weapon object first, set it up how I want, then add it to the Mech's weaponList NSSet object. But the core data selectors aren't working so I have to assume I am doing something wrong. Any advice here would be appreciated as I've dug through multiple books and guides and none of them really go in to depth about the process of handling these types of relationships... Thanks in advance for any advice. Cheers,
J^2
This error is not caused by the configuration of your data model. The:
unrecognized selector sent to instance
… error always results from having the wrong class in a variable for some reason.
In this case, the class Mech in the inputMech variable doesn't have a:
insertObject:inEquipmentListAtIndex:
...method.
The most likely cause of your error is that in the course of writing all this, you've created multiple copies of the Mech class files. One is configured for a ordered relationships and the other isn't. You are actually compiling with the one that does not.
In your second problem, you are simply sending a NSSet object to a method parameter that expects a Weapon object instead. You are confusing addWeaponListObject with addWeaponListObjects:
take the following steps
1) created a new version of the Core Data Model via Xcode.
2) Fix the relationship (added a new relationship between the two.enter link description here)
3) re-created the NSManagedObject subclass

Resources