I wasn’t able to find any documentation on how to override the CObject virtual methods Load, Save, and Compare to make use of(CList and CArrayObj) load, save, and sort features - so I managed to hack my way through it. I’m posting it here in case anyone else is interested in using the Save/Load/Sort methods in CArrayObj and CList. Also, if anyone has a better way please let me know.
#property strict
#include <Arrays\ArrayObj.mqh>
//+------------------------------------------------------------------+
class MyObj : public CObject
{
public:
string name;
double price;
datetime time;
virtual bool Save(const int file_handle) override // MUST BE OVERRIDDEN FOR LOAD/SAVE
{
if(!FileWriteString(file_handle,name,10)) return false;
if(!FileWriteDouble(file_handle,price)) return false;
if(!FileWriteLong(file_handle,(long)time))return false;
return(true);
}
virtual bool Load(const int file_handle) override // MUST BE OVERRIDDEN FOR LOAD/SAVE
{
name = FileReadString(file_handle,10);
price= FileReadDouble(file_handle);
time = (datetime)FileReadLong(file_handle);
return(true);
}
virtual int Compare(const CObject *node,const int mode=0)const override // MUST BE OVERRIDDEN FOR SORT
{
MyObj *other = (MyObj*)node;
if(this.price > other.price) return 1;
if(this.price < other.price) return -1;
return 0;
}
string ToString(){ return name+" - "+string(time)+" - "+string(price);}
};
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
class MyObjArray : public CArrayObj
{
public:
virtual bool CreateElement(const int index) override //MUST BE OVERRIDDEN FOR LOAD/SAVE
{
m_data[index] = new MyObj;
return true;
}
MyObj* operator[](const int i)const{return (MyObj*)At(i);}
bool Load()
{
int h = FileOpen("MyTest.bin",FILE_READ|FILE_BIN);
bool res = CArrayObj::Load(h);
FileClose(h);
return res;
}
bool Save()
{
int h = FileOpen("MyTest.bin",FILE_WRITE|FILE_BIN);
bool res = CArrayObj::Save(h);
FileClose(h);
return res;
}
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
srand(GetTickCount());
MyObjArray *arr = new MyObjArray;
int num = 1;
for(int i=0;i<SymbolsTotal(false)&&i<10;i++)
{
MyObj *obj = new MyObj;
obj.name = SymbolName(i,false);
obj.price= double(rand()%1000);
obj.time = TimeCurrent();
arr.Add(obj);
}
arr.Save();
delete arr;
arr = new MyObjArray;
arr.Load();
arr.Sort();
for(int i=0;i<arr.Total();i++)
Print(arr[i].ToString());
delete arr;
}
//+------------------------------------------------------------------+