【问题标题】:NSArray causes EXC_BAD_ACCESSNSArray 导致 EXC_BAD_ACCESS
【发布时间】:2012-03-05 23:43:08
【问题描述】:

我在一个类中声明一个 NSArray,如下所示:

.h

@interface HTTP : NSObject {
NSArray *listOfProfiles;
}
@property (nonatomic, retain) NSArray *listOfProfiles;

.m

-(id) init {
if ((self = [super init])) {
    listOfProfiles = [[NSArray alloc] init];
}
return self;
}

-(void) someMethod {
...
    case GET_LIST_OF_PROFILES:
        listOfProfiles = [result componentsSeparatedByString:@"^-^"];
        NSLog(@"first break: %@",[listOfProfiles objectAtIndex:0]);
        break;
...
}

我可以在这里很好地访问它,然后当我在创建对象后尝试在另一个类中访问它时,我收到错误 EXC_BAD_ACCESS 并且调试器转到 main.m:

- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
http = [[HTTP alloc] init];
[http createProfileArray];
profileListDelay = [[NSTimer alloc] init];
profileListDelay = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(profileListSelector) userInfo:nil repeats:YES];

}

- (void) profileListSelector 
{
if (http.activityDone)
{
    // http.listofprofiles mem leak?
    for (int i = 0; i < http.listOfProfiles.count; i++)
    {
        NSLog(@"%@",[http.listOfProfiles objectAtIndex:i]);
    }
    [profileListDelay invalidate];
    profileListDelay = nil;
}
}

我认为这可能是内存问题,但我可能完全错了。

【问题讨论】:

    标签: objective-c arrays memory-management nsarray


    【解决方案1】:

    这是内存问题

    someMethod

    -(void) someMethod {
    ...
        case GET_LIST_OF_PROFILES:
            listOfProfiles = [result componentsSeparatedByString:@"^-^"];
            NSLog(@"first break: %@",[listOfProfiles objectAtIndex:0]);
            break;
    ...
    }
    

    componentsSeparatedByString: 返回一个自动释放的对象
    由于您将数组声明为 retain 属性,因此您应该像这样更新它:

    self.listOfProfiles = [result componentsSeparatedByString:@"^-^"];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-27
      • 2016-11-19
      • 2012-10-02
      • 2011-04-14
      • 2017-03-15
      • 2014-09-27
      • 1970-01-01
      相关资源
      最近更新 更多