PDA

View Full Version : A help with QCache?



adutzu89
3rd March 2014, 15:19
I am trying to use the cache to store/retrieve data but I cannot actually figure it out how?
I didn't made a dedicated example for it so I just tested it with a login form, trying to store the user inside the cache and retrieve it on QDialog::exec().
I made a class

class InfoUtil{
public:
QString nUtil;
void setUtil(QString a);
const char* retUtil();
};

void InfoUtil::setUtil(QString a){
nUtil=a;
}
const char* InfoUtil::retUtil(){
return nUtil.toStdString().c_str();
}

Here is the block which checks if the login credentials are ok, and if they are it does emits some signals etc and cache the login user

if(util=="admin" && parola=="admin"){
QCache<const char*,InfoUtil> cache;
iu->setUtil(util);
cache.clear();
cache.insert(iu->retUtil(),iu);
}


util is a string which gets it's data from QLineEdit.
When the connection dialog opens it should have the cached "admin" set to the QLineEdit, but I get symbols.
Here is how I try to retrieve the data and set it to QLineEdit inside the dialog's constructor.

QCache<const char*,InfoUtil> cache;
const char* abc;
cache.take(abc);
txtUtil=new QLineEdit(abc);

I know it's wrong but can someone send me to the right direction?

ChrisW67
3rd March 2014, 20:49
Where to start...

To retrieve a value from QCache requires the same QCache you put the value in in the first place. In you code the QCache you insert into ceases to exist at the end of the if() block. The QCache you try to read from is a different instance, and one that cannot contain anything when you try to get stuff out of it.

In your read code you use a char* uninitialised (a fault) as cache key, ignore the return value from take() (the very thing take() exists to give you), and then use the unchanged uninitialised pointer to set the label text.

InfoUtil::retUtil() returns an unsafe pointer to the buffer of an object that has been destroyed.

QCache is not the right tool for storing the current value of anything you cannot afford to lose. QCache will delete values that have not been recently used if it needs to free space (it is size limited).

Perhaps you can explain what you are trying to achieve.

adutzu89
4th March 2014, 08:59
I'm trying to store some user info after he log's in, like it's ID and category until he logs out or close the program.
Something that can be persistant throught the program(meaning I can acces it from different classe's constructors or functions).

anda_skoa
4th March 2014, 09:33
I doubt you want to use a cache then. A cache can throw away entries when it needs space for new entries.

What you want is something that keeps the entry until you remove it explicitly (when the user logs out).

See QMap or QHash


Cheers,
_

adutzu89
4th March 2014, 15:31
Thank you for both your answers.