ioscore-plotnsmutableset

NSMutableSet not adding more than 1 object


I am creating a label (CorePlot) object in a for loop and trying to add it to NSMutableSet which I need to pass a a parameter.

Strangely only one object if added to the NSMutableSet (first one) and others are not added.

Looks like I am missing something very basic.

Any advice?

I am attaching screenshots of the code as I want to show the values held by the NSSet object.

Image 1 - Objects gets added to NSMutableArray but not to NSSet Forming From that array

Objects gets added to NSMutableArray but not to NSSet Forming From that array

Code used in Image 1 -

    NSArray *months = [NSArray arrayWithObjects:@"Oct",@"Nov",@"Dec",@"Jan",@"Feb",nil];
NSMutableArray *xLabels = [[NSMutableArray alloc] init];
for (NSString *month in months) {
    CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:month textStyle:axisTextStyle];
    [xLabels addObject:label];
}
NSSet *xLabelSet = [NSSet setWithArray:xLabels];
x.axisLabels = xLabelSet;

Image 2 - Objects not getting added to NSMutableSet Objects not getting added to NSMutableSet

Code used in Image 2 -

    NSArray *months = [NSArray arrayWithObjects:@"Oct",@"Nov",@"Dec",@"Jan",@"Feb",nil];
//NSMutableArray *xLabels = [[NSMutableArray alloc] init];
NSMutableSet *xLabelSet = [[NSMutableSet alloc] initWithCapacity:[months count]];
for (NSString *month in months) {
    CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:month textStyle:axisTextStyle];
    [xLabelSet addObject:label];
}
//NSSet *xLabelSet = [NSSet setWithArray:xLabels];
x.axisLabels = xLabelSet;

Solution

  • The documentation for the isEqual method for the CPTAxisLabel says -

    Axis labels are equal if they have the same tickLocation.

    As you aren't specifying the the tickLocation property for the labels you are adding they will all have the same tickLocation - 0.

    Since isEqual returns true for all of your labels you only end up with the first one in your NSSet - the addition of the subsequent label is skipped as an equal object is already in the set.