Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting NSArray to NSSet, custom class instances transfer inconsistently
    primarykey
    data
    text
    <p>Ran into a interesting little problem. I was writing a method to filter an array to the unique objects:</p> <pre><code>- (NSArray*)distinctObjectsByAddress { NSSet* uniqueSet = [NSSet setWithArray:self]; NSArray* retArray = [uniqueSet allObjects]; return retArray; } </code></pre> <p>and wrote a unit test to check:</p> <pre><code>- (void)testDistinctObjectsByAddress5 { Person* adam1 = [[Person alloc] initWithFirstName:@"adam" lastName:@"adam" andParent:nil]; Person* adam2 = [[Person alloc] initWithFirstName:@"adam" lastName:@"adam" andParent:nil]; testPersonArray = [NSArray arrayWithObjects:adam1,adam2, nil]; NSArray* checkArray = [testPersonArray distinctObjectsByAddress]; STAssertEquals([checkArray count], [testPersonArray count], @"Array %@ counts should match %@ %@",checkArray,adam1,adam2); } </code></pre> <p>Pretty simple. The interesting part is that about 80-90% of the time the test passes and every so often it fails because the <code>distinctObjectsByAddress</code> method only returns one object. I've been able to trace it to the <code>[NSSet setWithArray:self]</code> call but I've also been able to verify that the two person objects are two different objects (at least they have different address). I'm assuming that <code>setWithArray:</code> is just doing a basic address compare but I don't understand why it is sometimes producing two objects like it should and sometimes producing only one.</p> <p>Something I just tried was changing <code>adam2</code> so that the first and last name were not exactly the same as <code>adam1</code>. This seems to fix the error. Does this point to some sort of compiler optimization when the objects are logically the same?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload