Here is my code.. why it isn’t gonna add object to array when on device?
Maybe array can’t be read from file? I write file to documents directory, but what may be wrong? THanks…
if (contactsToProcess==nil)
{
contactsToProcess=[[NSMutableArray alloc] init];
NSLog(@"Array with objs initialized");
}
contactsToProcess=[NSKeyedUnarchiver unarchiveObjectWithFile:fPath()];
[contactsToProcess addObject:cont];
NSLog(@"Object added to file:");
for(Contact *cn in contactsToProcess)
{
NSLog(@"%@", cn.fName);
}
[NSKeyedArchiver archiveRootObject:contactsToProcess toFile:fPath()];
fPath() does:
NSString* PathforResources(NSString* filename)
{
NSString *leftpart=[filename stringByDeletingPathExtension];
NSString *extension=[filename pathExtension];
return [[NSBundle mainBundle] pathForResource:leftpart ofType:extension];
}
NSString* DocumentsDirectory()
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);
return [paths objectAtIndex:0];
}
NSString* fPath()
{
return [DocumentsDirectory() stringByAppendingPathComponent:@"quickdial.xml"];
}
I suppose you should change your code into:
then everything should work. Some explanation: the code as you posted will only work as you expect if the file
quickdial.xmlis already present; it will be specifically unable to create the file with a proper content (or to create it at all, I don’t know what is the exact effect of archiving anilpointer). Indeed, when the file does not exist, after executing you original code:contactsToProcesswill be nil; this means that all successive operation on it will have no effect and that you are archiving anilpointer. I.e, when the file does not exist, it will not be created with the array as you expect. This is what happens on your device.My hypothesis is that you ran the program in a different state on your simulator, and that your array got archived into the file successfully. Then you changed the program to the current state; on the simulator it keeps working because the file is there and contains an archived array. On the device the file is not created or just contains
nil, so it does not work as you expect.I would suggest removing the app from the device (tap on the app icon until you enter the dashboard editing mode, then tap on the delete button); then apply the change I suggested above and re-run.