I’d like to create a progress bar showing the status of a file reading.
I read the file using a C++ class Reader that contains a variable _progress.
How can I tell to Cocoa to update the progress bar with the value of reader._progress without writing any ObjC code in the Reader class?
Any help would be appreciated.
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);
So here is my second try.
The reader code:
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);
}
}
And the Cocoa part:
-(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();
}
Thanks for your help.
Finally!!!!!
It work’s well when do not put it into a queue.
But why do you say “This is bad, though, because it blocks the main thread”?
Because basically my program has to wait the file to be read before doing anything else.
Is there some basic optimization I miss here?
Thanks very much for your help.