How to persist data using archiving function on the iphone? - iphone

I am having trouble with persisting data.
Desired Behavior:
I have a text field defined in the view that captures user input. When the submit button is clicked (touch up inside), I expect to write that data to a mutable array. As of right now, I am going to archive that mutable array upon submit, but have also played with archiving once the view disappears/unloads. When a user navigates away from the view or exits the application and re-enters, I want to display the first element of that mutable array in the textfield.
Actual Behavior:
Textfield captures data and updates myMutableArray upon submitting. I have a few labels on the view plus NSLog to verify the count grows as I hit submit. I then archive this the first time, and I see that my file now exists in myDocuments plus when I revisit the view and check the count of dataArray, which is created if that file exists, the count of dataArray matches the number of elements I created in myMutableArray. If I start to enter in data again, it resets myMutableArray and dataArray all over again. That is one of a couple problems I think I have.
Questions:
If the file exists, then dataArray is created. Now I try to set the textfield to display the first element and the program bombs out! If dataArray exists, and I can see count is some positive value, I don't understand why I can't access that first element.
I feel like when I visit the view and go through this exercise, when I revisit the view I see I have dataArray present and with positive values, but when I start adding text again through the submit button, I reset everything! So I am persisting once maybe, but then wiping it clean. So much for real persistence. What am I doing wrong?
Eventually, I will be storing a record with a few elements. I will create multiple records over time for the user to review. Is archiving the best possible way? Should I start using NSCoding instead?
- (void)viewDidLoad {
[super viewDidLoad];
// Initialize mutable array and set equal to myMutableArray property
NSMutableArray *aMutableArray = [[NSMutableArray alloc] init];
myMutableArray = aMutableArray;
// Debug Logging
// NSLog(#"Mutable Array Count is: %i", [myMutableArray count]);
NSFileManager *filemgr;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
dataFilePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"data.archive"]];
// Check if the file already exists
if ([filemgr fileExistsAtPath: dataFilePath])
{
NSMutableArray *dataArray;
dataArray = [NSKeyedUnarchiver unarchiveObjectWithFile: dataFilePath];
myTextField.text = #"%#", [dataArray objectAtIndex:0]; // THIS BOMBS OUT MY PROGRAM FOR SURE IF INCLUDED!!!
//myUpdatedMutableArray = dataArray;
// Debug Logging
NSLog(#"Mutable Array (dataArray) Count is: %i", [dataArray count]);
//NSLog(#"The first value in the array is: %i", [dataArray objectAtIndex:0]);
}
[filemgr release];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (IBAction) mySubmitButtonPressed:(id)sender {
// Debug Logging
NSLog(#"Submit Button was Pressed!");
NSLog(#"Mutable Array (myMutableArray) Count is: %i", [myMutableArray count]);
// Create string from textfield and addobject to myMutableArray; check to see that myMutableArray grows in count
NSString *myString = [[NSString alloc] initWithFormat:#"%#",myTextField.text];
[myMutableArray addObject:myString];
NSLog(#"Mutable Array (myMutableArray) Count is: %i", [myMutableArray count]);
// More Debug Logging just using on-screen labels
NSString *mySecondString = [[NSString alloc] initWithFormat:#"%i", [myMutableArray count]];
myFirstLabel.text = myString;
mySecondLabel.text = mySecondString;
// Archive myMutableArray
[NSKeyedArchiver archiveRootObject: myMutableArray toFile:dataFilePath];
//[contactArray release];
}

There are many issues with this code.
To begin, you leak memory all over the place. Specifically here:
NSMutableArray *aMutableArray = [[NSMutableArray alloc] init];
myMutableArray = aMutableArray;
Which should really be:
self.myMutableArray = [NSMutableArray array];
After you unarchive the data, if you want to keep it in myMutableArray, simply do this:
[myMutableArray appendArray: dataArray];
Or just:
self.myMutableArray = dataArray;
You should never release singleton instances like the NSFileManager, so completely get rid of this one:
[fileMgr release];
Your code crashes because this is not valid code:
myTextField.text = #"%#", [dataArray objectAtIndex:0];
(It actually is valid code, but it will do something very different than you think)
This is not Python, so you will have to do this:
myTextField.text = [NSString stringWithFormat: #"%#",
[dataArry objectAtIndex: 0]];
But that is really the same as:
myTextField.text = [dataArray objectAtIndex: 0];
Adding a string to your array in mySubmitButtonPressed can be done much simpler than you think. Just do this:
[myMutableArray addObject: myTextField.text];
You should really learn about autoreleased objects, memory management and what retaining properties actually do.

Related

Can´t add objects to mutable array which returns nil

I´m doing an app and I can´t get a mutable array to accept objects. I´v tried setting breakpoints to see what´s happening but it keeps saying that the mutable array is nil. Does anyone has an answer?
My code:
- (void)save:(id) sender {
// All the values about the product
NSString *product = self.productTextField.text;
NSString *partNumber = self.partNumberTextField.text;
NSString *price = self.priceTextField.text;
NSString *quantity = self.quantityTextField.text;
NSString *weigh = self.weighTextField.text;
NSString *file = [self filePath];
//Singleton class object
Object *newObject = [[Object alloc] init];
newObject.product = product;
newObject.partNumber = partNumber;
newObject.price = price;
newObject.quantity = quantity;
newObject.weigh = weigh;
//Array declaration
mutableArray = [[NSMutableArray alloc]initWithContentsOfFile: file];
[mutableArray addObject:newObject];
[mutableArray writeToFile:file atomically:YES];
}
While initWithContentsOfFile: can be called on an NSMutableArray, it was inherited from NSArray. The return value is an NSArray which is not mutable. If you want to add objects to your mutable array, you have to do something like this:
mutableArray = [[[NSMutableArray alloc] initWithContentsOfFile: file] mutableCopy];
[mutableArray addObject:newObject];
[mutableArray writeToFile:file atomically:YES];
Now, the addObject: call should work.
Best regards.
[NSMutableArray initWithContentsOfFile:] returns nil by default if the file can't be opened or parsed. Are you sure the file you're loading exists and is formatted correctly?
Try to check with break point on
mutableArray = [[NSMutableArray alloc]initWithContentsOfFile: file];
Line. Move your cursor on mutableArray if it shows you __NSArrayI that means it is an immutable array i.e. you cant update it and if it shows you __NSArrayM that means it is a mutable array and you can update this array.
In your case you're getting immutable array thats why you cant update it.
So you have two way to get mutable Array from this file -
Method:1
mutableArray = [[[NSMutableArray alloc] initWithContentsOfFile: file] mutableCopy];
Method:2
NSArray *anyArray = [[NSArray alloc]initWithContentsOfFile: file];
mutableArray = [[NSMutableArray alloc]initWithArray:anyArray];
In both case mutableArray woud be a mutable Array. You can update it.

incompatible pointer types assigning to nsarray from nsdictionary

I'm new to iPhone development and have had great success with with answers from here so I am hoping to receive help directly. I am reading data into a tableview from a plist. The application works fine but I get 2 warnings when I compile. I know why I get the errors but I have been unsuccessful with resolving the issues. Although this app works I really would like to resolve the warnings efficiently. When I tried changing the NSDictionary to NSArray the warning goes away but the table is no longer populated.
Any help would be greatly appreciated.
Staff and Data are defined as NSArray in the Delegate .h file. The warnings show in the delegate .m file below.
My Delegate has the following:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:#"Data.plist"];
NSString *SPath = [[NSBundle mainBundle] bundlePath];
NSString *StaffPath = [SPath stringByAppendingPathComponent:#"Staff.plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
**self.data = tempDict;**
[tempDict release];
NSDictionary *staffDict = [[NSDictionary alloc]initWithContentsOfFile:StaffPath];
**self.staff = staffDict;**
[staffDict release];
In my staff ViewController I have the following:
if(CurrentLevel == 0) {
//Initialize our table data source
NSArray *staffDict = [[NSArray alloc] init];
self.tableDataSource = staffDict;
[staffDict release];
Midwest_DigestiveAppDelegate *AppDelegate = (Midwest_DigestiveAppDelegate *)[[UIApplication sharedApplication] delegate];
self.tableDataSource = [AppDelegate.staff valueForKey:#"Rows"];
}
else
self.navigationItem.title = CurrentTitle;
An NSArray holds a one dimensional list of items where an NSDictionary maps keys to values.
Array:
[a, b, c]
Dictionary:
{#"a" = #"first item", #"b" = #"second item"}
Could you declare data as NSDictionary *data; and populate it as data = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
You then access values in the dictionary with [data valueForKey:#"key"]
Everything in your code suggests that the staff and data properties are NSDictionary instances. You initialize them to dictionary objects and you reference them as dictionary objects. Why then are you declaring them as NSArray objects?
You should change how they are declared so they are NSDictionary in your header file rather than NSArray. That seems to me the most logical way to remove your warnings.
This should still work assuming the contents of your "staff" NSDictionary has a key named "Rows" whose value is an NSArray. The code you have to initialize self.tableDataSource with an empty NSArray seems redundant, as you immediately overwrite the value with the
self.tableDataSource = [AppDelegate.staff valueForKey:#"Rows"];
line in your code

Memory Leak the second time the view loads

i been cracking my head over this memory leak..
my datasource is mutabledictionary..that i load in the viewdidload. if i dont retain it. i dont have access it it in cellforrowatindexpath. but when i retain it.. it shows up as a memory leak in instruments. i have tried so many different variations.. doesnt seem to get it right.
here is the code the leak is in "dict" and "plistPath"
`
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationController.navigationBarHidden = NO;
self.title = #"Messages & Lists";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[plistPath release];
plistPath = [documentsDirectory stringByAppendingPathComponent:#"general.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[dict release];
if ( [fileManager fileExistsAtPath:plistPath] ) {
dict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath] ;
} else {
dict = [NSMutableDictionary dictionaryWithCapacity:1];
[dict setObject:#"NO" forKey:#"busyStatus"];
[dict setObject:#"NO" forKey:#"replyToAll"];
[dict setObject:#"NO" forKey:#"replyToList"];
[dict setObject:#"NO" forKey:#"dontReplyToList"];
[dict writeToFile:plistPath atomically:YES];
}
[tableData release];
tableData = [[NSMutableDictionary alloc] init];
[tableData setObject:[NSArray arrayWithObjects:#"Help",#"Set Default Message",#"Reply To All",[dict objectForKey:#"replyToAll"],nil] forKey:#"1"];
[tableData setObject:[NSArray arrayWithObjects:#"Reply to a List",[dict objectForKey:#"replyToList"],#"List of Contacts",nil] forKey:#"2"];
[tableData setObject:[NSArray arrayWithObjects:#"Don't reply to List",[dict objectForKey:#"dontReplyToList"],#"List of Contacts",nil] forKey:#"3"];
[dict retain];
[plistPath retain];
}
`
there is no leak the first time the view loads. but if i got back. and then load the view again it leaks.
thanks in advance for anyone who can help me out.
You have to call [dict release] in your view controller's dealloc method.
I think you should release your dictionary in the dealloc method of your view controller so that the retain count of your datasource is decreased when the ViewController is deallocated.
Retaining without releasing after use is the main source of memory leak.
It seems right.
The only thing that confuses me is the tableData. Is that var released or allocated somewhere else too?
Say you do allocate it somewhere else, and not releases it in dealloc, shouldn't these be the steps then:
tableData is allocated somewhere else.
tableData is released in viewDidLoad
tableData is allocated again (counter 1).
Exiting view, entering view again, tableData allocated again, released and allocated in function (counter two?)
Seems like a longshot, but. Can you display what the instruments say?

Creating Arrays from a plist file in iphone SDK 3.3 and up : objective c

I have run into this issue and have put some major time into finding the answer. I am somewhat new to objective c but not to programming.
Here is my question.
I have a plist file with this structure
root {
A (
{songTitle : contents of song},
{songTitle : contents of song}
),
B (
{songTitle : contents of song}
),
C (
{songTitle : contents of song}
),
... kepps going
}
Sorry if the the plist structure is not correct.
Pretty much I have a root dictionary (that is what it comes with) that contains an array of A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,...Z (alphabet)
Each letter of the alphabet array contains 1 or more dictionaries that have a key, value pair of songTitle (this could be any string) as the key and the song lyrics for the value.
My issue here is I need to create an array of all song titles and have been having a rough time trying to find out how to do this. I own 4 books on object c and none of them go into detail about multidimensional arrays and how to access pieces inside them.
I have created an array with all the letters and have created an array that contains the objects from each letter.
Like I stated before I need to find out how to make an array that contains each song title.
If you can help me that would save me a lot of time.
Thanks,
Wes
I am guessing you are suggesting I change my root from a dictionary to an array?
Maybe it might be better to show my code here.
Also I have attached an updated version of my plist file
Sorry seems I cannot add the image here but you can view it
http://www.wesduff.com/images/forum_images/plist_examp.png
So as you can see I have updated the plist file to show the array of letters that each contain multiple dictionaries. Each dictionary has a songTitle and a songLyrics.
How can I write code to get an array of songTitles.
Here is what I have come up with so far
NSString *path = [[NSBundle mainBundle] pathForResource:#"songs" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
//This gives me an array of all the letters in alphabetical order
NSArray *array = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
/**
Now I need to find out how to get an array of all songTitles
**/
I am still working on this and looking through what others have written but have not found anything yet.
As the first answer has suggested, should I change the root to an array or keep it as I have it in this plist image I have attached.
Thanks again,
Wes
Ok so I did some more digging and came up with this from the plist file that was included in this picture
http://www.wesduff.com/images/forum_images/plist_examp.png
- (void)viewDidLoad {
//path for plist file
NSString *path = [[NSBundle mainBundle] pathForResource:#"songList" ofType:#"plist"];
//dictionary created from plist file
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
//release the path because it is no longer needed
[path release];
//temp array to hold an array of all alphabetical letters
NSArray *array = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
//assign array to allLetters array
self.allLetters = array;
//Create two mutable arrays for the songArray (could do a little cleaner job of this here)
NSMutableArray *songArray = [[NSMutableArray alloc] init];
NSMutableArray *songTitles = [[NSMutableArray alloc] init];
//Add messy array to songArray then we can work with the songArray (maybe something better to do here)
for(id key in dict)
{
[songArray addObject:[dict objectForKey:key]];
}
//temp array to hold a messy array for all of the songTitles
NSArray *tempArray = [songArray valueForKey:#"songTitle"];
//go through the temparray and clean it up to make one array of all song titles and sort them
for (NSUInteger i = 0; i < [tempArray count]; i++) {
[songTitles addObjectsFromArray:[[tempArray objectAtIndex:i] sortedArrayUsingSelector:#selector(compare:)]];
}
//assign all song titles to our array of songTitles
self.allSongTitles = songTitles;
[dict release];
[allSongTitles release];
[songArray release];
[tempArray release];
[array release];
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
I am sure there is probably a better way to do this but this is what I have come up with on my own. Thanks
If you have single array with the contents of all the letters, the rest is fairly simple. Iterate through the objects and call the dictionary method allKeys on each one. Each call to allKeys will return an NSArray containing the keys of that specific dictionary, which you can then place into another array.
EDIT
I made a mistake, didn't go deep enough. This is what I would do:
NSString *path = [[NSBundle mainBundle] pathForResource:#"songs" ofType:#"plist"];
NSDictionary plistDict = [NSDictionary dictionaryWithContentsOfFile:path]; //not using alloc and init means this isn't retained, so it will be autoreleased at the end of the method
NSArray *allLetterContents = [plistDict allValues]; // array of arrays, where each element is the content of a 'letter' in your plist (i.e. each element is an array of dictionaries)
NSMutableArray *allSongTitles = [[[NSMutableArray alloc] init] autorelease];
for(NSArray *oneLetterContents in allLetterContents)
{
for(NSDictionary *song in oneLetterContents)
{
[allSongTitles addObject:[song objectForKey:#"songTitle"]]
}
}
return allSongTitles;
This array isn't guaranteed to be sorted alphabetically, so you'll have to call [sortedArrayUsingSelector:] on it.
Reference:
NSMutableArray Class Reference
NSDictionary Class Reference

Objective c, Memory Leak, reading from sqlite and assigning values to a NSDictionary and NSAarray

I have a list of shops in a ListController file.
I've setted up a sqlite db, in which i've stored 60 shops.
On the top of the list i have a search bar.
I've made a class called DataController, that is responsible to load and store db datas.
#interface DataController : NSObject {
sqlite3 *database;
NSArray *shops;
NSDictionary* dictionaryOfShops;
}
#property (nonatomic, retain) NSDictionary *dictionaryOfShops;
#property (nonatomic, retain) NSArray* shops;
-(void)initializeShops;
initializeShops method loads data from the db, and stores results into the 2 props in this way:
-(void)initializeShops{
[dictionaryOfShops release];
[shops release];
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
if (sqlite3_open(....))
NSString *query = ....
if (sqlite3_prepare_v2(database, [query UTF8String],-1, &statement, nil) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW) {
int rId = sqlite3_column_int(statement, 0);
char *rName = (char *)sqlite3_column_text(statement, 1);
Shop* s = [[Shop alloc] init];
s.ID = rId;
if(sName != nil) s.Name = [NSString stringWithUTF8String:rName];
NSString *shopID = [[NSString alloc] initWithFormat:#"%d",s.ID];
[dictionary setObject:s forKey:shopID];
[shopID release];
[s release];
}
sqlite3_finalize(statement);
}
[query release];
dictionaryOfShops = [[NSDictionary alloc] initWithDictionary:dictionary];
shops = [[NSArray alloc] initWithArray:[dictionary allValues]];
dictionary = nil;
[dictionary release];
//Sorting
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"Name" ascending:YES];
NSArray *sortedList =[self.shops sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
self.shops = sortedList;
[sort release];
}
The problem is that when user enters some text into the search
bar, I change the value of the query (adding LIKE....) and then call the initializeShops method again. This second time makes
so many leaks, (related to the Shop class properties) and
leaks also a NSDictionary and a NSArray.
Before posting this to you I've tried different solutions, but
at least this doesn't leaks anything the first time I call
initilizeShops.
I accept any suggestion, since I'm really stuck
on it.
MORE:
The really strange thing is memory management of my var dictionary and the 2 props shops and dictionaryOfShops. With this code
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
//add data to dictionary
dictionaryOfShops = [[NSDictionary alloc] initWithDictionary:dictionary];
shops = [[NSArray alloc] initWithArray:[dictionary allValues]];
[dictionary release]
Considering that dictionaryOfShops and shops are two properties (nonatomic,retain) synthesized, how can I change value to them without leaks?
The very first time I pass through this method nothing gets leaked, from the second time it starts to leak so many objects (the contents of the collections).
The first question is Why not just use Core Data? It is very likely going to be faster, will require less code, and will be significantly easier to maintain over time. To be blunt; SQLite is deceptively hard. Easy to get started, exceptionally difficult to get right.
In any case, the memory management of dictionary is wrong. It only isn't crashing because you swapped the order of the nil assignment and release as kennyTM suggested. I would suggest not creating an autoreleased dictionary.
Otherwise, the code as written seems pretty leakless at first glance. So:
Can you provide some more code?
Anything interesting memory wise
going on elsewhere?
Are you using threading at all (or
NSOperationQueue)?
Have you run under the Leaks
instrument and retrieved the
backtraces of allocation of the
specific objects being leaked?
dictionary = nil;
[dictionary release];
Please swap these 2 statements. In this form it means [nil release] which is a no-op.
Ok, I've found the error.
In my class Shop, i realize i didn't implement the method
-(void)dealloc
So when I release the old dictionary (to prepare for a new assignment), all the fields inside of it didn't get released.