我有一些主要由数据驱动的应用程序,因此大多数屏幕基本上由以下部分组成:


开启萤幕
通过NSOperation下载数据
在UITableView中显示数据
从UITableView中进行选择
转到新屏幕,然后从步骤1重新开始


我发现所有内容都可以正常使用,但是如果用户离开应用程序一段时间后又回来,则在下一次NSOperation运行时出现EXC_BAD_ACCESS错误。用户是否将应用程序发送到后台似乎无关紧要,并且似乎仅在自建立上一个数据连接以来至少有几分钟的时间发生。

我意识到这一定是某种形式的过度释放,但是我的内存管理相当不错,而且我看不到任何错误。我的数据调用通常如下所示:

-(void)viewDidLoad {
    [super viewDidLoad];

    NSOperationQueue* tmpQueue = [[NSOperationQueue alloc] init];
    self.queue = tmpQueue;
    [tmpQueue release];
}

-(void)loadHistory {
    GetHistoryOperation* operation = [[GetHistoryOperation alloc] init];
    [operation addObserver:self forKeyPath:@"isFinished" options:0 context:NULL];
    [self.queue addOperation:operation];
    [operation release];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqual:@"isFinished"] && [object isKindOfClass:[GetHistoryOperation class]]) {
        GetHistoryOperation* operation = (GetHistoryOperation*)object;
        if(operation.success) {
            [self performSelectorOnMainThread:@selector(loadHistorySuceeded:) withObject:operation waitUntilDone:YES];
        } else {
            [self performSelectorOnMainThread:@selector(loadHistoryFailed:) withObject:operation waitUntilDone:YES];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(void)loadHistorySuceeded:(GetHistoryOperation*)operation {
    if([operation.historyItems count] > 0) {
        //display data here
    } else {
        //display no data alert
    }
}

-(void)loadHistoryFailed:(GetHistoryOperation*)operation {
    //show failure alert
}


我的操作通常如下所示:

-(void)main {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSError* error = nil;
    NSString* postData = [self postData];
    NSDictionary *dictionary = [RequestHelper performPostRequest:kGetUserWalkHistoryUrl:postData:&error];

    if(dictionary) {
        NSNumber* isValid = [dictionary objectForKey:@"IsValid"];
        if([isValid boolValue]) {
            NSMutableArray* tmpDays = [[NSMutableArray alloc] init];
            NSMutableDictionary* tmpWalksDictionary = [[NSMutableDictionary alloc] init];
            NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyyMMdd"];

            NSArray* walksArray = [dictionary objectForKey:@"WalkHistories"];
            for(NSDictionary* walkDictionary in walksArray) {
                Walk* walk = [[Walk alloc] init];
                walk.name = [walkDictionary objectForKey:@"WalkName"];
                NSNumber* seconds = [walkDictionary objectForKey:@"TimeTaken"];
                walk.seconds = [seconds longLongValue];

                NSString* dateStart = [walkDictionary objectForKey:@"DateStart"];
                NSString* dateEnd = [walkDictionary objectForKey:@"DateEnd"];
                walk.startDate = [JSONHelper convertJSONDate:dateStart];
                walk.endDate = [JSONHelper convertJSONDate:dateEnd];

                NSString* dayKey = [dateFormatter stringFromDate:walk.startDate];
                NSMutableArray* dayWalks = [tmpWalksDictionary objectForKey:dayKey];
                if(!dayWalks) {
                    [tmpDays addObject:dayKey];
                    NSMutableArray* dayArray = [[NSMutableArray alloc] init];
                    [tmpWalksDictionary setObject:dayArray forKey:dayKey];
                    [dayArray release];
                    dayWalks = [tmpWalksDictionary objectForKey:dayKey];
                }
                [dayWalks addObject:walk];
                [walk release];
            }

            for(NSString* dayKey in tmpDays) {
                NSMutableArray* dayArray = [tmpWalksDictionary objectForKey:dayKey];

                NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"startDate" ascending:YES];
                NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
                NSArray* sortedDayArray = [dayArray sortedArrayUsingDescriptors:sortDescriptors];
                [sortDescriptor release];

                [tmpWalksDictionary setObject:sortedDayArray forKey:dayKey];
            }

            NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(localizedCompare:)];
            self.days = [tmpDays sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
            self.walks = [NSDictionary dictionaryWithDictionary:tmpWalksDictionary];
            [tmpDays release];
            [tmpWalksDictionary release];
            [dateFormatter release];
            self.success = YES;
        } else {
            self.success = NO;
            self.errorString = [dictionary objectForKey:@"Error"];
        }
        if([dictionary objectForKey:@"Key"]) {
            self.key = [dictionary objectForKey:@"Key"];
        }
    } else {
        self.errorString = [error localizedDescription];
        if(!self.errorString) {
            self.errorString = @"Unknown Error";
        }
        self.success = NO;
    }

    [pool release];
}

-(NSString*)postData {
    NSMutableString* postData = [[[NSMutableString alloc] init] autorelease];

    [postData appendFormat:@"%@=%@", @"LoginKey", self.key];

    return [NSString stringWithString:postData];
}

----
@implementation RequestHelper

+(NSDictionary*)performPostRequest:(NSString*)urlString:(NSString*)postData:(NSError**)error {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kHostName, urlString]];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
    [urlRequest setHTTPMethod:@"POST"];
    if(postData && ![postData isEqualToString:@""]) {
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
        [urlRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
        [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    }

    NSURLResponse *response = nil;
    error = nil;
    NSData *jsonData = [NSURLConnection sendSynchronousRequest:(NSURLRequest *)urlRequest returningResponse:(NSURLResponse **)&response error:(NSError **)&error];

    NSString *jsonString = [[NSString alloc] initWithBytes: [jsonData bytes] length:[jsonData length]  encoding:NSUTF8StringEncoding];
    NSLog(@"JSON: %@",jsonString);

    //parse JSON
    NSDictionary *dictionary = nil;
    if([jsonData length] > 0) {
        dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:error];
    }

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    return dictionary;
}


如果我有自动释放池,则崩溃发生在[pool release]上。如果我不这样做,那么崩溃看起来只是出现在main.m方法中,而且我似乎也没有得到任何有用的信息。我必须在每次测试之间等待10分钟才能追踪到!

如果有人可以提供任何线索或指导,将不胜感激。

最佳答案

几乎可以肯定,您在代码中过度释放了某些内容,因为该崩溃发生在[pool release]期间(主要方法中也有一个autorelease池)。

您可以使用Xcode找到它-使用构建和分析功能让静态分析仪查明潜在的问题。运行它并发布结果。

10-07 16:21
查看更多