简体   繁体   中英

ARC two-way relationship

So I want to have multiple nodes that are connected. Every node has outgoing and incoming connections. But the NSMutableArrays are creating leaks although i'm using ARC. How can i get the objects to be released properly? I'm already using an autoreleasepool. 草图

The code so far is:

@interface TestObj()
@property(strong) NSMutableArray *incoming;
@property(strong) NSMutableArray *outgoing;
@end

@implementation TestObj
@synthesize incoming,outgoing;

- (id)init
{
    self = [super init];
    if (self) {
        incoming = [NSMutableArray array];
        outgoing = [NSMutableArray array];
    }
    return self;
}

-(void)addIncoming:(TestObj *)incomingN {
    if([incoming indexOfObject:incomingN] == NSNotFound) {
        [incoming addObject:incomingN];
        [incomingN addOutgoing:self];
    }
}

-(void)addOutgoing:(TestObj *)outgoingN {
    if([outgoing indexOfObject:outgoingN] == NSNotFound) {
        [outgoing addObject:outgoingN];
        [outgoingN addIncoming:self];
    }
}

With ARC, as with manual memory management on iOS, you need to avoid retain cycles. If you have one object that is retaining a second, and the second is retaining the first, those two will never be deallocated even if nothing else references them, so you have a memory leak.

You need to make it so that you aren't referencing them like this. NSArray and NSMutableArray keep strong references to other objects. You can do something like the following to create a weak reference that you can story in the array:

NSValue *val = [NSValue valueWithNonretainedObject:object];

If you store val in the array, it won't have a strong reference to the object, so it can be deallocated. However, you have to be careful that you aren't creating a situation where some of your objects have no strong references, or they will get deallocated before you want them to.

好吧,这听起来很基本,但是尝试将它们设置为nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM