Issue adding TObjArray to a TList

I am using root 5.34/5 on windows. I have some code that stores a bunch of TObject derived objects in a TList and then later writes those objects to a new file:

    TList *objList = new TList();
    TObject *obj;
    while (obj = strIn->GetMyObject))    // returns TObject derived object or zero

Later I write these to a file:

    TIter next(objList);
    while (obj=next())

One of the objects is a TObjArray with a name “PeakRatioArray”. As it happens, the TObjArray has (at this point) only one object in it named “PeakRatio”. The resulting file does not have my TObjArray object named “PeakRatioArray” but instead has the contained object named “PeakRatio”. Is there a way for me to actually write the TObjArray itself rather than its contents? Thanks

Hi eoltman,

By default a TObjArray will write its contents to a file independently (i.e. each element is written with its own key) as you have seen. To write them so that the TObjArray is stored in the TFile rather than the individual elements, you need to pass the TObject::kSingleKey option in the Write method. You can see the difference produced by the code below.

    TObjArray arr;
    arr.Add(new TH1F("h0","h0",100,0,1));
    arr.Add(new TH1F("h1","h1",100,0,1));
    arr.Add(new TH1F("h2","h2",100,0,1));

    TFile *f0 = new TFile("f_allindiv.root","UPDATE");
    // write h0, h1, and h2 independently to the file

    TFile *f1 = new TFile("f_alltogether.root","UPDATE");
    // writes the TObjArray to file with the name "arr"

thanks much! That does it