views:

63

answers:

2

hello all , i am written app for my iphone and i want to save some NSmutablearray to file and load it later. i read about NSArchiver but didnt understand how to work with my calss is :

@interface Shop : NSObject 
{    
    NSString       *m_Name;
    NSString       *m_Description;
    NSString       *m_Category;
    NSString       *m_BestSaleDesc;
    NSString       *m_AdditionalInfo;   
    NSInteger       m_ShopId;
    NSInteger       m_ChainId;
    NSMutableArray *m_SalesList;
    NSData         *m_Icon;
    bool            m_Filtered;
    bool            m_Deleted;
    bool            m_Hidden;
}

can someone give me example code of how to save an NSmutableArray of calss Shop to file name ShopFile.sav and then how to load it again to NSmutableArray object.
thanks so much

A: 

Why not use Core Data? Core Data

ennuikiller
+1  A: 
NSArray *save = m_SalesList;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"/ShopFile.sav"];
[save writeToFile:filePath atomically:YES];

Should work. To load:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"/ShopFile.sav"];
NSArray *load = [NSArray arrayWithContentsOfFile:filePath];
m_SalesList = [NSMutableArray arrayWithArray:load];

This saves it to the documents directory in a file called "ShopFile.sav"

If you want to have your "Shop" NSObject in the array, simply use:

[m_SalesList addObject:(Shop class here)];
HiGuy Smith
its look like good example but i didnt see anywhere in the code where i save NSmutablearray of shops??? I only see NSArray *save = m_SalesList;
Amir
"Save" is a copy of your array, and then "save" is written to the file "Shopfile.sav" in the app's Documents directory. You could use [m_SalesList writeToFile: atomically:], but this is my method ;)This assumes that your array is already set up. If you want to create your array, that's a different question.
HiGuy Smith
but as you can see m_SalesList is not my Shop list its just a member in the Shop class that represent another list of somthing.i want to save list of Shops (m_ShopList) that every member of this list contain the members of class Shop(you can see is the top of the page) and one of those members is SalesList.you think that [m_ShopList writeToFile: atomically:] will do the job?i dont need to archive or serialize the list?many thanks
Amir
[m_ShopList writeToFile:atomically:] should work, unless I am misinterpreting what you said. Try testing it, and if it doesn't work, I'll keep thinking.
HiGuy Smith
thanks i will check that today and let you know
Amir