Reputation: 13
I'm trying to sort an NSMutableArray of Strings into alphabetical order and display the sorted list in an UIPickerView. I'm using another NSArray to create a sorted list.
Im using the PickerView Delegate Methods and have included them in my .h setup: and connected the dataSource & delegate outlets to the filesOwner. In my .h file I have also created an IBOutlet UIPickerView *pickerView; and created a synthesised property for it like this:
@property (nonatomic, retain) IBOutlet UIPickerView *pickerView;
Trying to troubleshoot the problem, I firstly made my unsorted NSMutableArray the source by doing the following:
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [pickerArray objectAtIndex:row];
}
My unsorted MutableArray has no issues and displays the data (unsorted) in the PickerView without problems but when I change the array to my sorted NSArray I get a crash after trying to move the PickerView!? An NSLog of the items in both arrays reveals the same number of items, the same data (displayed differently obviously) however Xcode reports a EXC_BAD_ACCESS?? I can't figure this one out??
Here is my code: (Note: sortedPickerArray is an NSArray and pickerArray is an NSMutableArray declared in my .h file)
- (void)viewDidLoad{
[super viewDidLoad];
sortedPickerArray = [[NSArray alloc] init];
pickerArray = [[NSMutableArray alloc] initWithObjects:
@"ObjectA",
@"ObjectB",
@"ObjectC",
@"ObjectD",
nil];
sortedPickerArray = [pickerArray sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
[pickerView selectRow:0 inComponent:0 animated:NO];
pickerView.showsSelectionIndicator = YES;}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component{
return [sortedPickerArray count];
}
-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [sortedPickerArray objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSLog(@"Row %d was selected", row);
}
Any help on this would be greatly appreciated.
Upvotes: 1
Views: 1716
Reputation: 18363
I'm assuming in this answer that you're not using ARC since you have a retained property. You assign an autoreleased value to your instance variable with the statement:
sortedPickerArray = [pickerArray sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
When you access sortedPickerArray
later on it has already been deallocated. So, again assuming you're not using ARC, add a retain
in there. And delete the line
sortedPickerArray = [[NSArray alloc] init];
as you are leaking this array as of now.
Upvotes: 1