objective-c - 在 Cocoa 中读取带进度条的文件

标签 objective-c multithreading macos cocoa grand-central-dispatch

我想创建一个进度条来显示文件读取的状态。 我使用包含变量 _progress 的 C++ 类 Reader 读取该文件。

如何告诉 Cocoa 使用 reader._progress 的值更新进度条,而无需在 Reader 类中编写任何 ObjC 代码?

如有任何帮助,我们将不胜感激。

ProgressController *pc = [[ProgressController alloc] init];
[pc showWindow:sender];


// Create the block that we wish to run on a different thread
void (^progressBlock)(void);
progressBlock = ^{
    [pc.pi setDoubleValue:0.0];
    [pc.pi startAnimation:sender];

    Reader reader("/path/to/myfile.txt");
    reader.read();

    while (reader._progress < 100.)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [pc.pi setDoubleValue:reader._progress];
            [pc.pi setNeedsDisplay:YES];
        });
    }
}; // end of progressBlock

// Finally, run the block on a different thread
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, progressBlock);
<小时/>

这是我的第二次尝试。

读者代码:

class PDBReader
{
public:
Reader(const char *filename);
Reader(string filename);
~Reader();

int read();

string _filename;
float _progress;

void setCallback(void (^cb)(double))
{
    if (_cb)
    {
        Block_release(_cb);
        _cb = Block_copy(cb);
    }
}
void (^_cb)(double);

protected:
private:
};



int Reader::read()
{
string buffer;
unsigned atomid = 0;
ifstream file;
file.open(_filename.c_str(), ifstream::in);

if (!file.is_open())
{
    return IOERROR;
}

file.seekg(0, ios_base::end);
float eof = (float) file.tellg();
file.seekg(0, ios_base::beg);

while (getline(file, buffer))
{
    _progress = (float) file.tellg() / eof * 100.;
    if (_cb)
    {
        _cb(_progress);
    }
        // some more parsing here...
    }
file.close();
return SUCCESS;
}

PDBReader::~PDBReader()
{
if (_cb)
{
    Block_release(_cb);
}
}

cocoa 部分:

-(IBAction) test:(id) sender
{
ProgressController *pc = [[ProgressController alloc] init];
[pc showWindow:sender];

Reader reader("test.txt");

reader.setCallback(^(double progress) 
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [pc.pi setDoubleValue:progress]; 
        [pc.pi setNeedsDisplay:YES];
    });
});

reader.read();
}

感谢您的帮助。

最佳答案

仅仅因为您不想让 Reader 包含 Objective-C 代码并不意味着您只能从外部观察它。它可以通过传入的函数指针调用 C 函数。它可以使用更通用的仿函数(函数对象)机制。它甚至可以占用一个 block 。

你绝对不想这样做while (reader._progress < 100.)环形。这是一个繁忙的循环。它将以计算机尽可能快的速度更新进度。它将 CPU 核心固定在 100% 利用率。事实上,它将任务排队到主调度队列的速度可能比任务运行的速度要快。

您只想在阅读器更新其 _progress 时更新进度指示器成员,这需要 Reader 类的某种合作。

关于objective-c - 在 Cocoa 中读取带进度条的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10014884/

相关文章:

iphone - 横向的 iPad 框架宽度和高度混合

ios - 如何在 Xcode 构建完成时设置警报?

iphone - NSURL 错误过多

ios - AFNetworking 使用 PUT 请求上传图片?

iphone - iPhone 中的下拉 ListView

c# - ReplaySubject.First() 意外阻塞

c - 使用 OMP 中的线程生成相同的随机数

java - 为什么java中多线程写文件速度较慢

objective-c - 动态读取和过滤 XML 文件

macos - 尽管建议修复 Mac OS X Yosemite,但 GIT SSL 错误仍然存​​在