问题
I have a PlaceAnnotation class that I fill into an NSMutableArray. In viewDidLoad, i initiate ihatethis
_ihatethis = [[NSMutableArray alloc]init];
I use a MKLocalSearchCompletionHandler to search. And handle the mapitems like this:
for (MKMapItem *mapItem in [response mapItems]){
PlaceAnnotation *place = [[PlaceAnnotation alloc] init];
[place assignTitle:[[mapItem placemark] name];
[_ihatethis addObject:place];
}
[_ihatethis removeObjectAtIndex:2]; /*BAD ACCESS HERE*/
[_tableView reloadData];
This is my PlaceAnnotation.h file
@interface PlaceAnnotation : CLPlacemark <MKAnnotation>
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, readonly, copy) NSString *title;
@property (nonatomic) NSDictionary* dict;
//@property (nonatomic) NSURL *url;
@property (nonatomic) NSString *phoneNum;
@property (readonly) BOOL selected;
-(void)assignTitle:(NSString *)newTitle;
-(void)assignSelected:(BOOL) boolVal;
This is my PlaceAnnotation.m file
#import "PlaceAnnotation.h"
@interface PlaceAnnotation ()
@property (readwrite) NSString *title;
@property (readwrite) BOOL selected;
@end
@implementation PlaceAnnotation
-(void) assignTitle:(NSString *)newTitle {
if ( ![newTitle isEqualToString:[self title]]){
self.title = newTitle;
}
}
-(void) assignSelected:(BOOL)boolVal{
self.selected = boolVal;
}
@end
@end
This is my first post, I have read a ton of answers that responded to exc_bad_access questions and I cannot figure this out. So I think that somehow the placeannotations are getting forgotten and released. So when i go to delete is later it is gone. I really am confused and angry.
回答1:
If the crash really is in this line [_ihatethis removeObjectAtIndex:2];
and it's a EXC_BAD_ACCESS then there are two possibilities:
_ihatethis
is pointing to a broken array (unlikely, if the loop went through).- An object in the array has been overreleased or has broken memory management in its
dealloc
method.
回答2:
It may be that you're trying to remove an item at an index greater than the array's count. Try to output the count just before [_ihatethis removeObjectAtIndex:2];
, like this:
`
NSLog(@"count: %d", [_ihatethis count]);
[_ihatethis removeObjectAtIndex:2]; /*BAD ACCESS HERE*/
`
If the count is smaller than 3, then you're trying to remove an object at an index outside the array's bounds.
回答3:
I changed this
@interface PlaceAnnotation : CLPlacemark <MKAnnotation>
to this
@interface PlaceAnnotation : NSObject <MKAnnotation>
so i guess the problem was with the dealloc of CLPlacemark. Thanks
来源:https://stackoverflow.com/questions/20204417/exc-bad-access-after-populating-nsmutablearray-with-custom-class-extending-clpla