Exc bad access after populating NSMutableArray with custom class extending CLPlacemark

耗尽温柔 提交于 2019-12-11 09:15:58

问题


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:

  1. _ihatethis is pointing to a broken array (unlikely, if the loop went through).
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!