简体   繁体   中英

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 aa 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

对象被添加到NSMutableArray,但不添加到该数组的NSSet Forming

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 对象未添加到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;

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.

I don't see the error on your code but I would suggest using CFMutableSetRef since it has a Toll-Free Bridging capability. Using it will enable you to give it as the parameter you need.

Maybe using the messages (methods) from CFMutableSetRef will enable you to add more objects.

Another thing I would try is simply doing an array with the CPTAxisLabels and using the method addObjectsFromArray from the NSMutableSet and check if that works.

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