NSMutableArrays and code for collection methods


I’m trying to apply the principals of indexOfObject and indexOfObjectIdenticalTo so that I can have a better understanding of how they work.

I’m not having much luck coming up with creating a small array and then trying to get output that shows where two of the items are equal, but not identical and then shows two items that are identical (and thus equal). Can someone help me out by posting some code that would do this?


Haven’t tested this, but you should be able to do something akin to this to create 3 objects to add to an array, all of which are equal, but only two of which are identical.

NSString *a = [NSString initWithString:@"Foo"];
NSString *b = a;
NSString *c = [NSString initWithString:a];

a & b should be identical, c should be equal but not identical to a/b.


Crap. I put this on the wrong board. Should have been 21. I’ll try that code out in just a bit though.


Ok… So this is my issue…

//  main.m
//  TestingIdenticals
//  Created by Chris H on 1/30/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])

    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        // Checking out the objects that are identical
        NSMutableArray *identicals = [[NSMutableArray alloc] init];
        NSString *a = [NSString stringWithFormat:@"Foo"];
        NSString *b = a;
        NSString *c = [NSString stringWithFormat:a];
        [identicals addObject:a];
        [identicals addObject:b];
        [identicals addObject:c];
        NSLog(@"A is: %@", a);
        NSLog(@"B is: %@", b);
        NSLog(@"C is: %@", c);
        NSLog(@"%p", &a);
        NSLog(@"%p", &b);
        NSLog(@"%p", &c);
        NSUInteger identicalsIndex = [identicals indexOfObjectIdenticalTo:[identicals objectAtIndex:2]];
        if (identicalsIndex == NSNotFound) {
            NSLog(@"NSNotFound for indexOfObjectIdenticalTo");
        NSUInteger index = [identicals indexOfObject:[identicals objectAtIndex:1]];
        if (index == NSNotFound) {
            NSLog(@"NSNotFound for indexOfObject");
    return 0;

The contents of each address are the same, and so are the addresses. That’s why I wrote them out, so I could see what they were. I’m not sure if I’m even using the methods at the bottom correctly though.

Edit: So the address of C is different, but I can’t seem to get the indexOfObjectIdenticalTo to run the if statement.