-1

我正在我的应用程序中创建一个计数器。我想在发生特定更改时增加它。计数器将它的值从 0 增加到 1。然后它坚持到 1 并且进一步它不增加。这是我的代码。在 .hi 中已经这样做了。

@interface URLCacheConnection : NSObject {
  int                     counter;

}

在 .m 中它有

-(void) connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse self]]) {

    printf("[(NSHTTPURLResponse *)response allHeaderFields] = %s\n", [[(NSHTTPURLResponse *)response suggestedFilename] cStringUsingEncoding: 1]);
    NSDictionary *dict = [(NSHTTPURLResponse *)response allHeaderFields];
    NSLog(@"allHeaderFields = %@\n", [dict description]);

    if(downloadItem.downloadStatus != DownloadStatus_resumed)
    {
        if([[NSFileManager defaultManager] fileExistsAtPath: downloadItem.fileItem.filePath]) {
            counter = counter + 1;
            NSLog(@"the value of counter is %d", counter);

            NSString * fileExtension = [downloadItem.fileItem.fileName pathExtension];

            NSString *fileName = [downloadItem.fileItem.fileName  stringByDeletingPathExtension];

            fileName = [fileName stringByAppendingFormat:@"-(%d)", counter]; 
            fileName = [fileName stringByAppendingString:[NSString stringWithFormat:@".%@",fileExtension]];

            downloadItem.fileItem.fileName  = fileName;

            downloadItem.fileItem.filePath = [NSString stringWithFormat:@"%@/%@", downloadItem.fileItem.folderPath, downloadItem.fileItem.fileName];
        }
        else {
            counter = 0;
        }
        BOOL fileCreatedFlag = [[NSFileManager defaultManager] createFileAtPath: downloadItem.fileItem.filePath contents:nil attributes:nil];
        downloadItem.fileItem.fileHandle = [NSFileHandle fileHandleForWritingAtPath: downloadItem.fileItem.filePath];
        fileCreatedFlag = fileCreatedFlag;

    }

}

}

4

3 回答 3

3

詹姆斯这是因为self.counter它将返回一个值而不是变量,因此它将打印不同的地址。请按照Keety在上述评论中
的建议提供准确的日志和使用日志。

于 2012-05-10T05:52:37.653 回答
1

如果下载状态恢复,则将计数器重置为 0。如果出于参数考虑,每次下载至少恢复一次,那么当您将其打印到日志时,计数器将始终为 1。

于 2012-05-11T00:44:27.513 回答
0

尝试这个:

NSInteger counter = 0;
counter = counter+1;
NSLog(@"the address of counter is %p",counter);
于 2012-05-10T05:53:47.230 回答