I have an NSMutablearray that I have data saved to. Data is input on my main ViewController. When you tap on a saved item, the SecondViewController has a textfield that the data entry is loaded into in order to be edited. I want to be able to edit that item and then save it back to the array.
I am fairly new to Objective-C / Cocoa Touch so please go easy on me.
- (ToDoItem *) updateToDoItem: (ToDoItem *) todoitem {
NSLog(#"ToDoItemSvc.updateToDoItem: %#", [todoitem description]);
NSMutableArray *toDoItems = [NSMutableArray array];
for (NSString *todoitem in toDoItems) {
if ([[ToDoItem] isEqualToString:toDoItems]) {
[toDoItems replaceObjectAtIndex:todoitem];
}
}
I know this isnt completely correct and may be completely off base but Im hoping I am moving in the right direction with this.
EDIT
Here is my ToDoItemSvcArchive.m file
#import "ToDoItemSvcArchive.h"
#implementation ToDoItemSvcArchive
NSString *filePath;
NSMutableArray *toDoItems;
- (id) init {
NSArray *dirPaths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
filePath = [[NSString alloc] initWithString: [docsDir
stringByAppendingPathComponent: #"ToDoItems.archive"]];
[self readArchive];
return self;
}
- (void) readArchive {
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: filePath])
{
toDoItems = [NSKeyedUnarchiver unarchiveObjectWithFile: filePath];
}
else
{
toDoItems = [NSMutableArray array];
}
}
- (void) writeArchive {
[NSKeyedArchiver archiveRootObject:toDoItems toFile:filePath];
}
- (ToDoItem *) createToDoItem: (ToDoItem *) todoitem {
NSLog(#"ToDoItemSvc.createToDoItem: %#", [todoitem description]);
[toDoItems addObject:todoitem];
[self writeArchive];
return todoitem;
}
- (NSMutableArray *) retrieveAllToDoItems {
return toDoItems;
}
- (ToDoItem *) updateToDoItem: (ToDoItem *) todoitem {
NSLog(#"ToDoItemSvc.updateToDoItem: %#", [todoitem description]);
NSMutableArray *toDoItems = [NSMutableArray array];
for (NSString *todoitem in toDoItems) {
if ([[ToDoItem] isEqualToString:toDoItems]) {
[toDoItems replaceObjectAtIndex:todoitem];
}
}
// return todoitem;
}
- (ToDoItem *) deleteToDoItem: (ToDoItem *) todoitem {
NSLog(#"ToDoItemSvc.deleteToDoItem: %#", [todoitem description]);
[toDoItems removeObject:todoitem];
[self writeArchive];
return todoitem;
}
#end
EDIT
I guess what I dont really understand is how to get the actual index of the object that needs to be replaced.
Edit
I think this is better
- (ToDoItem *) updateToDoItem: (ToDoItem *) todoitem {
NSLog(#"ToDoItemSvc.updateToDoItem: %#", [todoitem description]);
NSUInteger index = [toDoItems indexOfObject:todoitem];
[toDoItems replaceObjectAtIndex:0 withObject:todoitem];
return todoitem;
}
Im still not sure how to specify the correct index.
Over complicating the entire thing
Changed todoitemtext to todoitemobject and made it a todoitem rather than an NSString. Now when I click update, it updates the object and when you go back to the list, the view calls reloaddata and the view is updated with the new object
- (IBAction)updateToDoItem:(id)sender {
NSLog(#"updatingToDoItem: entering");
toDoItemObject.todoitem = toDoItem.text;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
toDoItem.text = toDoItemObject.todoitem;
}
Works like a champ now.
Related
As i'm beginner iOS, i just want to read a simple property list file (plist) in my program but it shows me the message "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController dataFilePath]: unrecognised selector sent to instance 0x15638660'". Kindly help me out where I had issue in program.
(.h file)
#interface ViewController : UIViewController {
NSString *listPath;
NSMutableArray *array;
}
- (NSString *) dataFilePath;
- (void) writePlist;
- (void) readPlist;
(.m file)
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
UIButton *readBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; readBtn.frame = CGRectMake(110,110,72,39);
[readBtn setTitle:#"Read" forState:UIControlStateNormal];
[readBtn addTarget:self action:#selector(readPlist)forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:readBtn];
UIButton *writeBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
writeBtn.frame = CGRectMake(110,210,72,39);
[writeBtn setTitle:#"Write" forState:UIControlStateNormal];
[writeBtn addTarget:self action:#selector(writePlist) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:writeBtn];
[super viewDidLoad];
}
- (NSString *)DocDirectories {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *DocumentDirectory=[path objectAtIndex:0];
return [DocumentDirectory stringByAppendingString:#"Data.plist"];
}
- (void)writePlist
{
NSMutableArray *anArray = [[NSMutableArray alloc]init];
[anArray addObject:#"A"];
[anArray addObject:#"B"];
[anArray writeToFile:[self dataFilePath] atomically:YES];
}
- (void)readPlist
{
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
NSLog(#"%#\n", array);
NSLog(#"%#\n",filePath);
// [array release];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
}
you view controller not has method dataFilePath.
you need to call function DocDirectories.
- (void)writePlist
{
NSMutableArray *anArray = [[NSMutableArray alloc]init];
[anArray addObject:#"A"];
[anArray addObject:#"B"];
[anArray writeToFile:[self DocDirectories] atomically:YES];
}
Hope this will help you.
Check this
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#“Data” ofType:#"plist"];
NSArray *arrData = [NSArray arrayWithContentsOfFile:plistPath];
Use this ,you will get
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Info" ofType:#"plist"]];
NSLog(#"dictionary = %#", dictionary);
NSArray *array = [dictionary objectForKey:#"CFBundleSupportedPlatforms"];
NSLog(#"array = %#", array);
Where is your dataFilePath function?
You should replace the function dataFilePath with DocDirectories.
try this:
- (NSString *)dataFilePath {
return [self DocDirectories];}
Add this function to your viewController.m.This issue is the compiler can't find the function:dataFilePath when the app is running, because you only decelerate dataFilePath in a .h file, you should also implement it in .m file.
I have an array of Objects (containing an item name and a creation date) used to display table data. I want to save this array using NSCoding protocol. I call my saveDataToDisk method every time a "submit" button is pressed to submit a new table entry. However, my app crashes upon hitting submit. This is my first time learning how to save app data and I looked a several tutorials and my form seems to be the same. I also looked for several days on the internet and couldn't find a solution. What is wrong?
Here are my methods:
Decoder Method:
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.itemArray = [decoder decodeObjectForKey:#"itemArray"];
return self;
}
Encoder Method:
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.itemArray forKey:#"itemArray"];
}
Path Finder Method:
- (NSString*) pathForDataFile
{
NSFileManager * fileManager = [NSFileManager defaultManager];
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"appData"];
if([fileManager fileExistsAtPath:filePath] == NO)
{
[fileManager createDirectoryAtPath:filePath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *fileName = #"Budgetlist.appData";
return [filePath stringByAppendingPathComponent: fileName];
}
Save Data Method:
- (void) saveDataToDisk
{
NSString * path = [self pathForDataFile];
NSMutableDictionary * rootObject;
rootObject = [NSMutableDictionary dictionary];
[rootObject setValue: [self itemArray] forKey:#"itemArray"];
[NSKeyedArchiver archiveRootObject: rootObject toFile: path];
}
Load Data Method:
- (void) loadDataFromDisk
{
NSString * path = [self pathForDataFile];
NSDictionary * rootObject;
rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
[self setItemArray: [rootObject valueForKey:#"itemArray"]];
}
My Button:
- (IBAction)submitButton:(id)sender {
if (self.textField.text.length > 0 && [self.textField.text floatValue]>0) {
self.item = [[Data alloc] init];
self.item.itemName = self.textField.text;
[self.itemArray addObject:self.item];
[self.tableView reloadData];
[self saveDataToDisk];
}
}
You are trying to save an NSArray with custom objects.
Your objects must implement NSCoding protocol as well.
Implement those:
- (id)initWithCoder:(NSCoder *)decoder
- (void)encodeWithCoder:(NSCoder *)encoder
in your "Data" class.
NSArray is going through all objects and call those methods for each object inisde an array
New to iOS and am stuck on one issue in regards to adding objects in NSMutable Array and displaying the array on another view within the App. The data displays fine on other view in TableView, but when I add another item to the Array (using code below), it just replaces what was there, not adding to the array.
- (void) postArray {
tableData = [[NSMutableArray alloc] initWithCapacity:10];
tableData = [[NSMutableArray alloc] initWithObjects: nil];
[tableData addObject:favShot]; }
-(NSString *) saveFilePath {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
return [[path objectAtIndex:0] stringByAppendingPathComponent:#"savefile.plist"]; }
- (void) viewWillDisappear:(BOOL)animated: (UIApplication *) application {
NSArray *values = [[NSArray alloc] initWithObjects:tableData, nil];
[values writeToFile:[self saveFilePath] atomically: TRUE]; }
- (void)viewDidLoad {
tableData = [[NSMutableArray alloc] initWithObjects: nil];
NSString *myPath = [self saveFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists)
{
NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
tableData = [values mutable copy];
}
UIApplication *myApp = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:myApp];
[super viewDidLoad]; }
Thank you.
Every time you call postArray you're creating an instance of NSMutableArray, then throwing it away (leaking it if you aren't using ARC). Then you're creating another instance of NSMutableArray. Then you're adding an object (favShot) to that second instance.
Next time you call postArray it's going to throw away your old array and create 2 new ones.
What you want to do is create the tableData instance when you create the controller instance, or when the view loads. Then, don't set tableData = ... as that will discard the old instance. Just add and remove objects.
edit
- (void) postArray {
[tableData addObject:favShot];
}
- (NSString *)saveFilePath {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
return [[path objectAtIndex:0] stringByAppendingPathComponent:#"savefile.plist"];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[tableData writeToFile:[self saveFilePath] atomically: TRUE];
}
- (void)viewDidLoad {
NSString *myPath = [self saveFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists)
{
tableData = [[NSMutableArray alloc] initWithContentsOfFile:myPath];
} else {
tableData = [[NSMutableArray alloc] initWithObjects: nil];
}
UIApplication *myApp = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:myApp];
[super viewDidLoad];
}
Try
- (void) viewWillDisappear:(BOOL)animated: (UIApplication *) application
{
NSString *filePath = [self saveFilePath];
NSMutableArray *savedArray = [NSMutableArray arrayWithContentsOfFile:filePath];
if (!savedArray) savedArray = [NSMutableArray array];
[savedArray addObject:tableData];
[savedArray writeToFile:filePath atomically:YES];
}
i am developing very simple quiz app
In viewDidLoad i am adding objects in myarray
where ever i nslog myarray values it works fine
but if i try this inside ibaction methods all objects becomes zombie
for 2 days i am stuck in this but can't find it what is wrong.
quiz.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#class dbVals;
#class viewTransition;
#class AppDelegate;
#interface quiz : UIViewController
{
NSMutableArray *myarray;
IBOutlet UITextView *questionTextView_;
IBOutlet UIButton *skipButton_;
IBOutlet UIButton *optionAButton_;
IBOutlet UIButton *optionBButton_;
IBOutlet UIButton *optionCButton_;
NSString *correctAnswer;
int questionNumber;
int score;
IBOutlet UILabel *scoreLabel_;
int totalQuestions;
}
-(void)populate:(int)number;
//#property(nonatomic, retain) NSMutableArray *myarray;
#property (retain, nonatomic) IBOutlet UITextView *questionTextView;
#property (retain, nonatomic) IBOutlet UIButton *skipButton;
#property (retain, nonatomic) IBOutlet UIButton *optionAButton;
#property (retain, nonatomic) IBOutlet UIButton *optionBButton;
#property (retain, nonatomic) IBOutlet UIButton *optionCButton;
#property (retain, nonatomic) IBOutlet UILabel *scoreLabel;
- (IBAction)optionsToAnswer:(id)sender;
- (IBAction)zzz:(id)sender;
#end
quiz.m
#import "quiz.h"
#import "DbVals.h"
#import "viewTransition.h"
#import "AppDelegate.h"
#implementation quiz
#synthesize skipButton=skipButton_;
#synthesize optionAButton=optionAButton_;
#synthesize optionBButton=optionBButton_;
#synthesize optionCButton=optionCButton_;
#synthesize scoreLabel=scoreLabel_;
#synthesize questionTextView=questionTextView_;
//#synthesize myarray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)createEditableCopyOfDatabaseIfNeeded
{
//NSLog(#"Creating editable copy of database");
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
+(sqlite3 *) getNewDBConnection
{
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
//NSLog(#"Database Successfully Opened ");
} else {
NSLog(#"Error in opening database ");
}
return newDBconnection;
}
- (void)viewDidLoad
{
[super viewDidLoad];
questionNumber = 0;
score = 0;
[self createEditableCopyOfDatabaseIfNeeded];
sqlite3 *dbc = [quiz getNewDBConnection];
sqlite3_stmt *statement = nil;
const char *sqlSelect = "select * from QnA ORDER BY RANDOM()";
if(sqlite3_prepare_v2(dbc, sqlSelect, -1, &statement, NULL)!=SQLITE_OK)
{
NSAssert1(0, #"Error Preparing Statement", sqlite3_errmsg(dbc));
}
else
{
myarray = [[NSMutableArray alloc]init];
while(sqlite3_step(statement)==SQLITE_ROW)
{
NSString *q = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
NSString *o = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 1)];
NSString *a = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 2)];
DbVals *dbValsObj = [[DbVals alloc]init];
[dbValsObj setValsOfQuestions:q options:o answer:a];
[myarray addObject:dbValsObj];
[dbValsObj release];
}
}
sqlite3_finalize(statement);
//[self populate:questionNumber];
}
-(void)populate:(int)number
{
/*[scoreLabel_ setText:[NSString stringWithFormat:#"%d",score]];
AppDelegate *appDel = [[UIApplication sharedApplication] delegate];
[appDel setFinalScore:[NSString stringWithFormat:#"%d",score]];
if(number < [myarray count])
{
DbVals *dbv1 = [myarray objectAtIndex:number];
[questionTextView_ setText:[dbv1 getQuestions]];
NSString *joinedOptions = [dbv1 getOptions];
NSArray *splitOptions = [joinedOptions componentsSeparatedByString:#","];
[optionAButton_ setTitle:[splitOptions objectAtIndex:0] forState:UIControlStateNormal];
[optionBButton_ setTitle:[splitOptions objectAtIndex:1] forState:UIControlStateNormal];
[optionCButton_ setTitle:[splitOptions objectAtIndex:2] forState:UIControlStateNormal];
correctAnswer = [dbv1 getAnswer];
}
else
{
//viewTransition *vt = [[viewTransition alloc]init];
[viewTransition viewsTransitionCurrentView:self toNextView:#"result"];
//[vt release];
}*/
}
- (void)viewDidUnload
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<u><u><u><u><><><><><><><><><><><>");
}
[self setQuestionTextView:nil];
[questionTextView_ release];
questionTextView_ = nil;
[self setQuestionTextView:nil];
[skipButton_ release];
skipButton_ = nil;
[self setSkipButton:nil];
[optionAButton_ release];
optionAButton_ = nil;
[self setOptionAButton:nil];
[optionBButton_ release];
optionBButton_ = nil;
[self setOptionBButton:nil];
[optionCButton_ release];
optionCButton_ = nil;
[self setOptionCButton:nil];
[scoreLabel_ release];
scoreLabel_ = nil;
[self setScoreLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<d><d><d><d><d><><><><><><><><><><>");
}
[questionTextView_ release];
[skipButton_ release];
[optionAButton_ release];
[optionBButton_ release];
[optionCButton_ release];
[scoreLabel_ release];
[myarray release];
[super dealloc];
}
- (IBAction)optionsToAnswer:(id)sender
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"six");
}
if(sender == skipButton_)
{
//questionNumber++;
//[self populate:questionNumber];
/*[UIView animateWithDuration:5 delay:0 options: UIViewAnimationCurveEaseOut
animations:
^{
[UIView setAnimationTransition:103 forView:self.view cache:NO];
}
completion:
^(BOOL finished)
{
}
];*/
}
if(sender == optionAButton_)
{
/*NSString *one = #"1";
if([correctAnswer isEqualToString:one])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionBButton_)
{
/*NSString *two = #"2";
if([correctAnswer isEqualToString:two])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionCButton_)
{
/*NSString *three = #"3";
if([correctAnswer isEqualToString:three])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
}
- (IBAction)zzz:(id)sender
{
}
#end
dbVals.h
#import <Foundation/Foundation.h>
#interface DbVals : NSObject
{
NSString *questions_;
NSString *options_;
NSString *answer_;
// NSString *hint;
// NSString *mode;
}
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer;
-(NSString*)getQuestions;
-(NSString*)getOptions;
-(NSString*)getAnswer;
dbVals.m
#import "DbVals.h"
#implementation DbVals
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
questions_ = questions;
options_ = options;
answer_ = answer;
}
-(NSString*)getQuestions
{
return questions_;
}
-(NSString*)getOptions
{
return options_;
}
-(NSString*)getAnswer
{
return answer_;
}
#end
Your dbVals.m setVals isn't retaining the parameters. This obviously means, everything inside becomes deallocated once the function scope ends.
Try changing it to something like
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
[questions_ release];
[options_ release];
[answer_ release];
questions_ = [questions copy];
options_ = [options copy];
answer_ = [answer copy];
}
Once more I come to the Internet, hat in hand. :)
I'm attempting to use a class method to return a populated array containing other arrays as elements:
.h:
#interface NetworkData : NSObject {
}
+(NSString*) getCachePath:(NSString*) filename;
+(void) writeToFile:(NSString*)text withFilename:(NSString*) filePath;
+(NSString*) readFromFile:(NSString*) filePath;
+(void) loadParkData:(NSString*) filename;
+(NSArray*) generateColumnArray:(int) column type:(NSString*) type filename:(NSString*) filename;
#end
.m:
#import "NetworkData.h"
#import "JSON.h"
#import "Utility.h"
#implementation NetworkData
+(NSString*) getCachePath:(NSString*) filename {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *cachePath = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0], filename];
[paths release];
return cachePath;
}
+(void) writeToFile:(NSString*)text withFilename:(NSString*) filename {
NSMutableArray *array = [[NSArray alloc] init];
[array addObject:text];
[array writeToFile:filename atomically:YES];
[array release];
}
+(NSString*) readFromFile:(NSString*) filename {
NSFileManager* filemgr = [[NSFileManager alloc] init];
NSData* buffer = [filemgr contentsAtPath:filename];
NSString* data = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding];
[buffer release];
[filemgr release];
return data;
}
+(void) loadParkData:(NSString*) filename {
NSString *filePath = [self getCachePath:filename];
NSURL *url = [NSURL URLWithString:#"http://my.appserver.com"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];
}
+(NSArray*) generateColumnArray:(int) column type:(NSString*) type filename:(NSString*) filename {
// NSLog(#"generateColumnArray called: %u %# %#", column, type, filename);
// productArray = [[NSMutableArray alloc] init];
// NSString *filePath = [self getCachePath:filename];
// NSString *fileContent = [self readFromFile:filePath];
// NSString *jsonString = [[NSString alloc] initWithString:fileContent];
// NSDictionary *results = [jsonString JSONValue];
// NSArray *eventsArray = [results objectForKey:type];
// NSInteger* eventsArrayCount = [eventsArray count];
// NSInteger* a;
// for (a = 0; a < eventsArrayCount; a++) {
// NSArray *eventsColSrc = [eventsArray objectAtIndex:a];
// NSArray *blockArray = [eventsColSrc objectAtIndex:column];
// [productArray addObject:blockArray];
// [blockArray release];
// }
// [eventsArray release];
// [results release];
// [jsonString release];
// [fileContent release];
// [filePath release];
// [a release];
// [eventsArrayCount release];
// return productArray;
}
-(void)dealloc {
[super dealloc];
}
#end
.. and the call:
NSArray* dataColumn = [NetworkData generateColumnArray:0 type:#"eventtype_a" filename:#"data.json"];
The code within the method works (isn't pretty, I know - noob at work). It's essentially moot because just calling it (with no active code, as shown) causes the app to quit before the splash screen reveals anything else.
I'm betting this is a headslapper - many thanks for any knowledge you can drop.
If your app crashes, there's very likely a message in the console that tells you why. It's always helpful to include that message when seeking help.
One obvious problem is that your +generateColumnArray... method is supposed to return a pointer to an NSArray, but with all the code in the method commented out, it's not returning anything, and who-knows-what is being assigned to dataColumn. Try just adding a return nil; to the end of the method and see if that fixes the crash. Again, though, look at the error message to see specifically why the code is crashing, and that will lead you to the solution.
Well, you're not returning a valid value from your commented out code. What do you use 'dataColumn' for next? Running under the debugger should point you right to the issue, no?