1

I have two arrays, I want to print values by names and alias. They are NSString values.

I`m a beginner in obj-c. I will be glad to any help.

And I’ll add everything you need to understand the cause of the problem, thanks!

NSArray <VBHuman*> * arrayOfHumans = [NSArray arrayWithObjects:
                          human, cycler, runner, swimmer, boxer,
                          nil];

NSArray <VBAnimal*> * arrayOfAnimals = [NSArray arrayWithObjects:
                           animal, dog, cat, hamster,
                           nil];

NSArray* newArray = @[];
newArray = [newArray arrayByAddingObjectsFromArray:arrayOfHumans];
newArray = [newArray arrayByAddingObjectsFromArray:arrayOfAnimals];


[newArray sortedArrayUsingDescriptors:
 @[
   [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES],
   [NSSortDescriptor sortDescriptorWithKey:@"alias" ascending:YES]
   ]];

In results it doesn't work, it has type following:

[<VBAnimal 0x6000002520f0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.
2
  • What does VBAnimal and VBHuman look like? do they have the properties 'name' and 'alias'? Commented Feb 5, 2019 at 19:32
  • @JonRose .h looks like "@property (strong, nonatomic) NSString* name;" and animal have the same property but "@property (strong, nonatomic) NSString* alias;" Commented Feb 5, 2019 at 20:41

1 Answer 1

1

The error message tells you what's wrong:

[<VBAnimal 0x6000002520f0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.

When you use -sortedArrayUsingDescriptors:, NSArray uses the keys you give it to get values from the objects it's comparing in order to decide how to order the objects. If it can't determine the order from the first descriptor (because the values the objects return are the same), it moves on to the next descriptor, until either it determines the order or it runs out of descriptors.

So, when you sort your array, NSArray starts with the first key, i.e. @"name". If your VBAnimal class isn't KVC compliant for the key @"name", then you'll get the error above. There are at least three ways to implement key value coding for a given key:

  • provide a method with a name that matches the key and have it return a value
  • add a property with a name that matches the key
  • implement valueForKey: such that it returns a value for the key

You need to do one of those two for your VBAnimal class.

Sign up to request clarification or add additional context in comments.

2 Comments

Modern Objective-C: property.
@Willeke I'll add that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.