我正在我的应用中创建一个计数器。我希望在发生特定更改时增加它。计数器将其值从0增加到1.然后它会粘到1并且它不会增加。这是我的代码。在.h我做到了。
@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;
}
}
}
答案 0 :(得分:3)
詹姆斯这是因为self.counter
会返回一个值而不是变量,因此会打印不同的地址
请在上面的评论中提供确切的日志并使用 Keety 建议的日志。
答案 1 :(得分:1)
如果恢复下载状态,则将计数器重置为0.如果为了参数起见,每次下载至少恢复一次,那么当您将计数器打印到日志时,计数器将始终为1。
答案 2 :(得分:0)
试试这个:
NSInteger counter = 0;
counter = counter+1;
NSLog(@"the address of counter is %p",counter);