开发者

Comparing Objects in Objective-C

开发者 https://www.devze.com 2023-04-09 00:36 出处:网络
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:

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
    {
        NSStr开发者_如何学运维ing *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)?


If you read the documentation for indexOfObject:, you'd find that NSArray calls isEqual: for each object in the array. So, override isEqual for Notebook and implement your own comparison routine.

Apropos of nothing, why are you allocating without initializing an instance of Notebook, overwriting it with an autoreleased instance, and subsequently releasing that? (Never mind you might be releasing it in your loop first!) You're destined for a crash. And why are you removing objects from an array while you're iterating through it?


You want to implement methods like -isEqual:. Please have a look here.

0

精彩评论

暂无评论...
验证码 换一张
取 消