I am trying to compare objects in Objective-C and was just wandering how, for example, two objects (which are instances of UIView) are compared that hold two NSStrings like so:
#import <Foundation/Foundation.h>
@interface Notebook : UIView
{
NSString *nameOfBook;
NSString *colourOfBook;
}
@property (nonatomic, retain) NSString *nameOfBook;
@property (nonatomic, retain) NSString *colourOfBook;
Let's assume that I have two NSMutableArrays which hold several objects of the type Notebook. One is called reality and the other theory. Reality holds two notebooks with the nameOfBook @"Lectures"
and @"Recipies"
, but colourOfBook are all empty. Theory holds three notebooks with the nameOfBook @"Lectures"
, @"Recipies"
, @"Zoo"
, and colourOfBook @"red"
, @"yellow"
, @"green"
.
I would like to compare the two arrays and adjust theory according to reality. In this case, it would mean to remove @"Zoo"
. I can't simply replace theory with reality as I would loose all the colours stored in theory.
This is the code I've come up with:
for (int i=0; i < [theory count]; i++) {
Notebook *testedNotebook = [Notebook alloc];
testedNotebook = [theory objectAtIndex:i];
if ([reality indexOfObject:testedNotebook] == NSNotFound)
{
NSLog(@"Book is not found in reality - remove it from theory...");
[theory removeObject:testedNotebook];
}
[testedNotebook release];
}
Now, my big question is how the objects will be compared. Ideally, I'd like to compare ONLY their NAMES regardless of the COLOUR. But I guess this is not how my code works right now. The entire objects are compared and the object in reality which holds @"Lectures" and @"" (no colour) cannot be the same as the object in theory which holds @"Lectures" and @"red".
How could I achieve to compare objects according to one of their attributes only (in this case the name)?