My iOS app stalls on setDelegate for about 15 seconds after about 100,000 setDelegate calls. Changing the delegate property from weak to assign fixes the problem. Any idea why the weak property has so much overhead and stalls the app?
I suspect the weak references are maintained in an array so the runtime can loop thru them and set the pointers to nil when the delegate object gets deallocated. Does the array have a max size? The stall gets much longer as n nears 100,000.
Sample code is below:
Header file:
#import <Foundation/Foundation.h>
@protocol GraphDataPointDelegate <NSObject>
- (BOOL)drawGraphByDistance;
@end
@interface GraphDataPoint : NSObject
- (id)initWithYValue:(NSNumber *)yValue withTime:(NSNumber *)time withDistance:(NSNumber *)distance withDelegate:(id <GraphDataPointDelegate> )delegate;
@end
@interface Graph : NSObject <GraphDataPointDelegate>
@end
M File
#import "Graph.h"
@interface GraphDataPoint ()
@property (nonatomic, weak, readwrite) id <GraphDataPointDelegate> delegate;
@property (nonatomic, strong, readwrite) NSNumber *yValue;
@property (nonatomic, strong, readwrite) NSNumber *time;
@property (nonatomic, strong, readwrite) NSNumber *distance;
@end
@implementation GraphDataPoint
- (id)initWithYValue:(NSNumber *)yValue withTime:(NSNumber *)time withDistance:(NSNumber *)distance withDelegate:(id<GraphDataPointDelegate>)delegate {
self = [super init];
if (self) {
self.yValue = yValue;
self.time = time;
self.distance = distance;
self.delegate = delegate;
}
return self;
}
- (id)graphXValue {
if ([_delegate drawGraphByDistance]) {
return _distance;
} else {
return _time;
}
}
@end
@implementation Graph
- (id)init {
self = [super init];
if (self) {
NSMutableArray *array = [NSMutableArray array];
NSLog(@"before");
for (int i = 0; i < 100000; i++) {
GraphDataPoint *graphData = [[GraphDataPoint alloc] initWithYValue:@1 withTime:@1 withDistance:@1 withDelegate:self];
[array addObject:graphData];
}
NSLog(@"after");
}
return self;
}
- (BOOL)drawGraphByDistance {
return YES;
}
@end
weak
properties?assign
has no overhead but logs of danger.weak
has overhead but none of the danger.drawGraphByDistance
), the graph could simply pass that value as a parameter tographXValue
.