Entertaining bug


#1

In the 4t edition, the author says this [quote](For an entertaining bug, have both accessors automatically call the other. This creates an infinite loop:
addAsset: calls setHolder: which calls addAsset: which calls setHolder: which….)[/quote].

This is before adding this piece of code to BNRemployee.m:

a.holder = self;

For pure interest I tried to make the bug and thus create the infinite loop, but I still cant. Could someone help me with this, I would be very grateful.

Thank you.

PS: Sorry for my english.


#2

Your English is good.

And here is the entertaining bug, in a nut shell:

//  main.m

#import <Foundation/Foundation.h>

// ----------------------------------------------------------
//
@class Holder;

@interface Foo: NSObject

@property Holder * holder;

@end

// ----------------------------------------------------------
//
@interface Holder: NSObject

- (void)addFoo:(Foo *)foo;

@end

// ----------------------------------------------------------
//
int main (int argc, const char * argv[])
{
    @autoreleasepool {
        Foo * foo = [Foo new];
        foo.holder = [Holder new];
    }
    return 0;
}

// ----------------------------------------------------------
//
@implementation Foo
{
    Holder *_holder;
}

- (Holder *)holder
{
    return _holder;
}

- (void)setHolder:(Holder *)holder
{
    NSLog (@"%s", __PRETTY_FUNCTION__);
    _holder = holder;
    [_holder addFoo:self];
}

@end

// ----------------------------------------------------------
//
@implementation Holder
{
    NSMutableArray * _store;
}

- (void)addFoo:(Foo *)foo
{
    NSLog (@"%s", __PRETTY_FUNCTION__);
    
    if (!_store) {
        _store = [NSMutableArray array];
    }
    [_store addObject:foo];
    foo.holder = self;
}
@end
2014-09-18 11:53:46.332 RetainCycle[79699:303] -[Foo setHolder:]
2014-09-18 11:53:46.333 RetainCycle[79699:303] -[Holder addFoo:]
2014-09-18 11:53:46.333 RetainCycle[79699:303] -[Foo setHolder:]
2014-09-18 11:53:46.334 RetainCycle[79699:303] -[Holder addFoo:]
2014-09-18 11:53:46.334 RetainCycle[79699:303] -[Foo setHolder:]
2014-09-18 11:53:46.334 RetainCycle[79699:303] -[Holder addFoo:]
...

#3

Thank you very much for the help ibex. :smiley: