我有一个 NSMutableArray 作为视图控制器类中的属性,并且这条线正在其他两个类中使用。其中一个类操作数组(向其中添加更多对象),另一个类只是从中读取。当其中一个类操作数组时,它不会在实例化的视图控制器类中被修改。因此,第三个类没有得到它需要的正确日期。
在视图控制器类中:
@property (nonatomic, strong) NSMutableArray *entityLines;
在其他两个类中:
@property (nonatomic, weak) NSMutableArray *linesToDraw;
@property (nonatomic, weak) NSMutableArray *linesForKey;
数组初始化:
- (id)init
{
self = [super init];
if (self) {
self.title = @"Line graph";
lineQuery = [[LineGraphQuery alloc] init];
entityLines = [NSMutableArray array];
}
return self;
}
修改数组:
- (void)drawRect:(CGRect)rect
{
if(data.namedEntityData.count > 0) {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, LINE_WIDTH);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextFillRect(context, rect);
[self clearAllLines];
for(NSString *key in [data.namedEntityData allKeys]) {
EntityLine *entityLine = [self getNamedEntityLineForName:key];
if(!entityLine) {
entityLine = [[EntityLine alloc] init];
entityLine.name = key;
entityLine.color = [self getRandomColor];
}
float intervalX = STARTING_INTERVAL_X;
float lastRangeY = MIN_EVENT_COUNT_Y;
CGContextSetStrokeColorWithColor(context, [entityLine.color CGColor]);
NSArray *events = [data.namedEntityData objectForKey:key];
NSInteger rangeDifference = data.endYear - data.beginYear;
for(int i = 0; i < numberOfDateRangeIntervals; i++) {
int startYearRange = data.beginYear + (i * (rangeDifference / numberOfDateRangeIntervals));
int endYearRange = (i == numberOfDateRangeIntervals - 1) ? data.endYear : data.beginYear + ((i + 1) * (rangeDifference / numberOfDateRangeIntervals) - 1);
int eventCount = [self getCountForEvents:events withBeginYear:startYearRange andEndYear:endYearRange];
Line *line = [[Line alloc] init];
line.begin = CGPointMake(intervalX, lastRangeY);
CGContextMoveToPoint(context, line.begin.x, line.begin.y);
intervalX += intervalXIncrement;
lastRangeY = [self getYCoordinateForEventCount:eventCount];
line.end = CGPointMake(intervalX, lastRangeY);
[entityLine addLine:line];
CGContextAddLineToPoint(context, line.end.x, line.end.y);
CGContextStrokePath(context);
}
[linesToDraw addObject:entityLine];
}
[self drawEventCountLabelsWithContext:context];
[self drawDateRangeLabelsWithContext:context];
}
}
- (void)clearAllLines
{
for(EntityLine *line in linesToDraw)
[line clearLines];
}
其他类设置对 NSMutableArray 的引用:
lineGraph.linesToDraw = self.entityLines;
lineKey.linesForKey = self.entityLines;