NSArray of weak references (__unsafe_unretained) to objects under ARC

前端 未结 12 753
南旧
南旧 2020-11-27 11:26

I need to store weak references to objects in an NSArray, in order to prevent retain cycles. I\'m not sure of the proper syntax to use. Is this the correct way?



        
12条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 12:19

    If you use a lot this comportment it's indicated to your own NSMutableArray class (subclass of NSMutableArray) which doesn't increase the retain count.

    You should have something like this:

    -(void)addObject:(NSObject *)object {
        [self.collection addObject:[NSValue valueWithNonretainedObject:object]];
    }
    
    -(NSObject*) getObject:(NSUInteger)index {
    
        NSValue *value = [self.collection objectAtIndex:index];
        if (value.nonretainedObjectValue != nil) {
            return value.nonretainedObjectValue;
        }
    
        //it's nice to clean the array if the referenced object was deallocated
        [self.collection removeObjectAtIndex:index];
    
        return nil;
    }
    

提交回复
热议问题