我想创建一个显示文件读取状态的进度条。我使用包含变量 _progress 的 C++ 类阅读器读取文件。
我如何告诉 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);
}
}
还有可可部分:
-(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();
}
谢谢你的帮助。