- (NSMutableArray *) orderedComponents{
NSSortDescriptor *orderSort=[[NSSortDescriptor alloc] initWithKey:[ComponentToLabelMO order_Key]
ascending:YES];
//------------------------------------------------------^
NSArray *sorted=[[[self components] allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:orderSort]];
self.orderedComponents=[[NSMutableArray alloc] initWithArray:sorted]; //use self.property= to handle retention
return orderedComponents;
}
- (ComponentToLabelMO *) componentAtIndex:(NSUInteger) index{
return [self.orderedComponents objectAtIndex:index];
}
// I use the NSMutableArray methods to manage the order for me.
-(void) updateComponentOrder{
NSUInteger i, count = [self.orderedComponents count];
for (i = 0; i < count; i++) {
ComponentToLabelMO* component = [self.orderedComponents objectAtIndex:i];
component.order=[NSNumber numberWithUnsignedInt:i];
}
}
// creates new linking object and assigns it's order to the end of the label
- (void) addComponentToLabelWithComponent:(LabelComponentMO *) aLabelComponent{
ComponentToLabelMO *ctlMO=[NSEntityDescription insertNewObjectForEntityForName:[ComponentToLabelMO entityName]
inManagedObjectContext:self.managedObjectContext];
//------------------------------------------------^
ctlMO.label=self; //this will add the ctl automatically to self.components
ctlMO.component=aLabelComponent;
ctlMO.order=[NSNumber numberWithInt:[self.orderedComponents count]]; //the order is zero indexed so first labels order is zero, second is one etc
}
//Used to add a component to the end of the index i.e. when order is not known or needed
- (void) addComponent:(LabelComponentMO *) aLabelComponent;{
if (aLabelComponent!=nil) {
[self addComponentToLabelWithComponent:aLabelComponent]; //automatically add at end of order
[self updateComponentOrder];
}
}
// Used to add a component to a specific index in the lable
- (void) addComponent:(LabelComponentMO *) aLabelComponent AtIndex:(NSUInteger) index{
if (aLabelComponent!=nil) {
[self addComponentToLabelWithComponent:aLabelComponent];
[self.orderedComponents exchangeObjectAtIndex:[self.orderedComponents count] withObjectAtIndex:index];
[self updateComponentOrder];
}
}
- (void) swapComponentAtIndex:(NSUInteger) firstIndex withComponentAtIndex:(NSUInteger) otherIndex{
NSUInteger comCount=[self.orderedComponents count];
if ( (firstIndex<=comCount) && (otherIndex<=comCount) ){ // prevent range exception
[self.orderedComponents exchangeObjectAtIndex:firstIndex withObjectAtIndex:otherIndex];
[self updateComponentOrder];
}
}
- (void) removeComponentAtIndex:(NSUInteger) index{
if (index<=[self.orderedComponents count]) {
ComponentToLabelMO *removedLabel=[self.orderedComponents objectAtIndex:index];
[self removeComponentsObject:removedLabel];
[self updateComponentOrder];
}
}