How to pass array value from one class to other class - iphone

How can i pass an array value from a delegate class to view controller class
const char *query2=[tempQuery UTF8String];
NSMutableArray *arr1 = [[NSMutableArray alloc]init];;
if (sqlite3_prepare_v2(database,query2,-1,&statement1,NULL)==SQLITE_OK) {
//NSLog(#"vt", vt);
while (sqlite3_step(statement1)==SQLITE_ROW) {
vt=[[[Question1 alloc]init]autorelease];
vt.question=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement1,3)];
[arr1 addObject:vt.question];
NSLog(#"arr1 is %#",[arr1 description]);
Where arr1 is an array value. So that array value has to pass in another class.
Thanks in advance.

In a class where you want to pass this "arr1" array do following steps:
1) define a array there (lets say it is aryTest)
2) make property for it
3) synthesize it
Now in a view where you are getting this "arr1" array.
From this view when ever you write code to push to next view do following steps:
NextViewController *objVc = [[NextViewController alloc] initWithNibName:#"NextViewController" bundle:nil];
objVc.aryTest = arr1;
[self.navigationController pushViewController:vc animated:YES];
[vc release];
so by this you will get this arr1 array into next view in aryTest array.

just create a Array method like in +(NSMutableArray *)getData in delegate class
+(NSMutableArray *)getData
{
const char *query2=[tempQuery UTF8String];
NSMutableArray *arr1 = [[NSMutableArray alloc]init];;
if (sqlite3_prepare_v2(database,query2,-1,&statement1,NULL)==SQLITE_OK) {
//NSLog(#"vt", vt);
while (sqlite3_step(statement1)==SQLITE_ROW) {
[arr1 addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement1,3)]];
NSLog(#"arr1 is %#",[arr1 description]);
}
}
return [arr1 autorelease];
}
in your view controller just call the method like
NSMutableArray * data=[[delegate getData]retain];

Try creating the array in your appDelegate. Thus it can be accessible in any view controller by calling your appDelegate:
myAppDelegate *myDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
arrayInView = [myDelegate msgFilter];

You can pass NSString or NSMutableArray using NSUserDefault method...
NSUserDefaultExample and Saving/Retrieving Data Using NSUserDefaults
For Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:#"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:#"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:#"floatKey"];
// saving an array
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
[prefs setObject:data forKey:#"lastResults"]
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
For Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:#"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:#"floatKey"];
// getting an array
NSData *dataRepresentingSavedArray = [prefs objectForKey:#"lastResults"];
if (dataRepresentingSavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
objectArray = [[NSMutableArray alloc] init];
}
or
filename *detailViewController = [[filename alloc] initWithNibName:#"filename" bundle:nil];
detailViewController.audio=#"yourData";
[self presentModalViewController:detailViewController animated:YES];
[detailViewController release];
Declare in filename.h
NSArray *audio;
#property(nonatomic,retain) NSArray *audio;
and filename.m
#synthesize audio;
thats all.

Related

NSUserDefaults not getting stored string value

I have UIWebView for reading content. After that i select some text from content stores in string using NSUserDefaults in Viewcontroller. Then i retrieve this string value and displays in UITextView to viewcontroller1. But the UITextView is not updating text from viewcontroller. The NSUserDefaults also not getting updating text. Im using [self.navigationController pushViewController:viewcontroller1 animated:YES]; for switch to viewcontroller1.
viewcontroller:
[wbCont loadHTMLString:webString baseURL:nil];
[self.view addSubview:wbCont];
NSMutableArray *items = [[[UIMenuController sharedMenuController] menuItems] mutableCopy];
if (!items) items = [[NSMutableArray alloc] init];
UIMenuItem *menuItem;
menuItem = [[UIMenuItem alloc] initWithTitle:#"BookMark" action:#selector(save:)];
[items addObject:menuItem];
[menuItem release];
menuItem = [[UIMenuItem alloc] initWithTitle:#"Note" action:#selector(note:)];
[items addObject:menuItem];
[menuItem release];
[[UIMenuController sharedMenuController] setMenuItems:items];
[items release];
- (BOOL) canPerformAction:(SEL)action withSender:(id)sender
{
if (action == #selector(save:))
{
return YES;
}
else if (action == #selector(note:))
{
return YES;
}
else if (action == #selector(copy:))
{
return NO;
}
return [super canPerformAction:action withSender:sender];
}
-(void)save:(id)sender{
NSString *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSLog(#"selection is %#",selection);
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:selection forKey:#"preferenceName"];
[userData1 synchronize];
[self.navigationController pushViewController:note animated:YES];
}
viewcontroller1:
textView = [[UITextView alloc]initWithFrame:CGRectMake(0,0,320,400)];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedValue = [prefs stringForKey:#"preferenceName"];
NSLog(#"saved is %#", savedValue);
textView.text = [NSString stringWithFormat:#"%#", savedValue];
Allocation of textView is in viewDidLoad.
Updating of textView is in viewWillAppear.
-(void) viewWillAppear:(BOOL)animated
[super viewWillAppear:animated];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedValue = [prefs stringForKey:#"preferenceName"];
NSLog(#"saved is %#", savedValue);
textView.text = [NSString stringWithFormat:#"%#", savedValue];
}
I was checked your code just change NSSTring to NSString like below it will working.
-(void)save:(id)sender{
// NSSTring *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSString *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSLog(#"selection is %#",selection);
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:selection forKey:#"preferenceName"];
[userData1 synchronize];
[self.navigationController pushViewController:note animated:YES];
}

Just cannot figure out how to reloadData in UITableView using a navigationController

This is my first time asking a question & posting code so I hope I have included everything that is necessary.
In several of my other apps I have been able to successfully reloadData in a UITableView but for some reason I cannot get it to work here.
I am using a navigationController and drilling down a few levels in the UITableView until a new class loads which right now just has two buttons that switch between 2 similar plist files so I can tell that the tableView is actually reloading (Data.plist & Data2.plist)
This is eventually going to be a timesheet sort of app where individual jobs are listed and the user (driver) will punch a timeclock with In/Out buttons. For now, what I want is to drill down and click the button that loads the other plist and go back up to reveal that the new plist data has loaded. My problem is that I cannot get the tableView to reload at all. I've tried putting different variations of [self.tableView reloadData] & [myTableView reloadData] (which I have also connected via IB) all over the place but none of them work. I'm currently calling a method in the rootViewController (where the tableView is) from detailViewController (where the buttons are) and that basic process works for me in other apps when there is no navigationController being used. The navigationController seems to be throwing me off here in this app. I hope an easy solution can be found. My code so far looks like this:
AppDelegate.m
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
RootViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
//THIS ESTABLISHES WHICH PLIST TO LOAD BASED ON THE BUTTON CLICKED
plistToUse = [[NSUserDefaults standardUserDefaults] objectForKey:#"plistToUse"];
if (plistToUse == #"Data.plist") {
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:#"Data.plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
self.data = tempDict;
[tempDict release];
} else if (plistToUse == #"Data2.plist") {
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:#"Data2.plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
self.data = tempDict;
[tempDict release];
} else {
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:#"Data.plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
self.data = tempDict;
[tempDict release];
}
if(CurrentLevel == 0) {
NSArray *tempArray = [[NSArray alloc] init];
self.tableDataSource = tempArray;
[tempArray release];
self.tableDataSource = [self.data objectForKey:#"Rows"];
self.navigationItem.title = #"Choose Driver";
} else if (CurrentLevel == 1) {
self.navigationItem.title = #"Choose Day";
} else if (CurrentLevel == 2) {
self.navigationItem.title = #"Choose Job";
} else if (CurrentLevel == 3) {
self.navigationItem.title = #"Job Details";
} else {
self.navigationItem.title = CurrentTitle;
}
}
-(void)update {
dvController.labelHelper.text = #"UPDATED"; //USED TO SEE IF A LABEL IN THE BUTTON CLASS WILL UPDATE
NSArray *tempArray = [[NSArray alloc] init];
self.tableDataSource = tempArray;
[tempArray release];
self.tableDataSource = [self.data objectForKey:#"Rows"];
self.navigationController.navigationItem.title = #"Choose Driver";
self.navigationController.title = #"THE TITLE";
[myTableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
unsortedIndex=1;
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.tableDataSource count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
cell.textLabel.text = [dictionary objectForKey:#"Title"];
NSArray *Children = [dictionary objectForKey:#"Children"];
if ([Children count] == 0) {
Titles = [dictionary objectForKey:#"Title"];
in1 = [[NSUserDefaults standardUserDefaults] objectForKey:#"InTime1"];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", in1];
}
in1 = [[NSUserDefaults standardUserDefaults] objectForKey:#"InTime1"];
out1 = [[NSUserDefaults standardUserDefaults] objectForKey:#"OutTime1"];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#:%#", in1, out1];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
NSArray *Children = [dictionary objectForKey:#"Children"];
DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:[NSBundle mainBundle]];
if([Children count] == 0) {
[self.navigationController pushViewController:dvController animated:YES];
dvController.labelSiteName.text = [dictionary objectForKey:#"Company"];
dvController.labelSiteAddress.text = [dictionary objectForKey:#"Address"];
dvController.labelSiteNotes.text = [dictionary objectForKey:#"Notes"];
[dvController.mapView setMapType:MKMapTypeStandard];
[dvController.mapView setZoomEnabled:YES];
[dvController.mapView setScrollEnabled:YES];
dvController.mapView.showsUserLocation = YES;
[dvController release];
}
else {
RootViewController *rvController = [[RootViewController alloc] initWithNibName:#"RootViewController" bundle:[NSBundle mainBundle]];
rvController.CurrentLevel += 1;
rvController.CurrentTitle = [dictionary objectForKey:#"Title"];
[self.navigationController pushViewController:rvController animated:YES];
rvController.tableDataSource = Children;
[rvController release];
}
}
DetailViewController.m
These are the two buttons that should reload the tableView with either Data.plist or Data2.plist
-(IBAction)getInTime1:(id)sender {
plistToUse = #"Data.plist";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:plistToUse forKey:#"plistToUse"];
[defaults synchronize];
[rvController update];
}
-(IBAction)getOutTime1:(id)sender {
plistToUse = #"Data2.plist";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:plistToUse forKey:#"plistToUse"];
[defaults synchronize];
[rvController update];
}
I appreciate any help you can give.
Add your data fetching from plist code into your viewDidAppear or viewWillAppear methods, so that each time view appears, the data is loaded from plist.
And also note that your arrays are allocated only once.
This will work for you.

read and write using NSKeyedArchiver, ios

Below is a class to read and write data using nsarchive
Data.m
-(id)init {
self = [super init];
if(self) {
arr = [[NSMutableArray alloc] init];
}
return self;
}
-(NSString *)getPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath;
if ([paths count] > 0)
documentPath = [paths objectAtIndex:0];
NSString *draftDataPath = [documentPath stringByAppendingPathComponent:#"draftData.dat"];
return draftDataPath;
}
-(void)saveDataToDisk {
NSString *path = [self getPath];
[NSKeyedArchiver archiveRootObject:arr toFile:path];
}
-(void)loadDataFromDisk {
NSString *path = [self getPath];
self.arr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
At later on, I am adding some objects into arr by doing
CustomerClass.m
- (void) viewDidLoad {
Data *data = [[Data alloc] init];
[data.arr addObject:myObject1]
[data.arr addObject:myObject2]
[data.arr addObject:myObject3]
[data saveDataToDisk];
}
At DisplayData.m, I want to check data.arr by
- (void) viewDidLoad {
Data *data = [[Data alloc] init];
[data loadDataFromDisk];
NSLog(#"length of array is %d",[data.arr count]);
}
On the console, I am getting
length of array is 1
I thought it should be 3 after all.
Please point out what I have just made a mistake in the middle of work if you have any clues about it.
So, I suspect that your "myObjects" are not NSCoding compliant. I just did this:
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];
[arr addObject:#"Hello"];
[arr addObject:#" "];
[arr addObject:#"World"];
BOOL ret = [NSKeyedArchiver archiveRootObject:arr toFile:[self getPath]];
NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getPath]];
NSLog(#"count = %d", [arr2 count]);
And the results was "count = 3"
I feel like there's too much code here to do what you're looking for. I think all you need is:
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dataClass] forKey:NSUserDefaultString];
[[NSUserDefaults standardUserDefaults] synchronize];
to save it.
And:
NSData *someData = [[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultString];
if (settingsData != nil)
{
dataClass = [NSKeyedUnarchiver unarchiveObjectWithData:settingsData];
}
to retrieve it.

NSUserDefault to NSArray

Icstored the value of 2 label in NSUserDefault, trought NSMutableArray.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary new];
[bookmark setValue:author.text forKey:#"author"];
[bookmark setValue:book.text forKey:#"book"];
[bookmarks addObject:bookmark];
// Save your (updated) bookmarks
[userDefaults setObject:bookmarks forKey:#"bookmarks"];
[userDefaults synchronize];
Now my problem is how retrieve the values of NSUserDefault trought NSArray?
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
self.dataArray = [prefs arrayForKey:#"bookmarks"];
NSString *author = ??
NSString *book = ??
NSString * author = [self.dataArray objectForKey: #"author"];
NSString * book = [self.dataArray objectForKey: #"book"];
This assumes you successfully saved the array and that you successfully re-loaded the array from NSUserDefaults. You really should do some error checking in your code.
In the dataArray, you can store lots of bookmarks.This methods can log all of the bookmarks.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
self.dataArray = [prefs objectForKey:#"bookmarks"];
for(int i=0;i<[dataArray count];i++){
NSDictionary *dic = [dataArray objectAtIndex:i];
NSLog(#"%#",dic);
NSString * author = [dic objectForKey: #"author"];
NSString * book = [dic objectForKey: #"book"];
}
you have inserted an array with a dictionary. you can retrieve it by using
self.dataArray = [prefs arrayForKey:#"bookmarks"];
NSString *author = [self.dataArray objectAtIndex:0] objectForKey:#"author"];
NSString *book = [self.dataArray objectAtIndex:0] objectForKey:#"book"];
But it is better to store the dictionary directly in user defaults.

Fail to addObject to NSMutableArray

I am building this 'Add to favorite' with NSUserDefault. I am having this issue when adding array to NSMutableArray. Does anyone knows what I did wrong? Thank you very much.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *favoriteRecipes = [[NSMutableArray alloc] init];
if ([prefs objectForKey:#"myFavor"] == nil) {
//create the array
NSMutableArray *array = [[NSMutableArray alloc] init];
[prefs setObject:array forKey:#"myFavor"];
[array release];
}
NSMutableArray *tempArray = [[prefs objectForKey:#"myFavor"] mutableCopy];
favoriteRecipes = tempArray;
[tempArray release];
NSArray *charArray = [[NSArray alloc] initWithObjects: #"test1", #"test2" , nil];
//add the recipe
[favoriteRecipes addObject:[charArray objectAtIndex:0]];
//save the array to NSUserDefaults
[prefs setObject:favoriteRecipes forKey:#"myFavor"];
[prefs synchronize];
favoriteRecipes = tempArray;
instated of above line use be below line it will work fine
[favoriteRecipes addObjectsFromArray:tempArray];
done something like this yesterday. see my code below. im not sure if you want the same thing like I did.
NSDictionary *tempDictionary = [NSDictionary dictionaryWithObjectsAndKeys:productID,#"ID",productTitle,#"title",productPrice,#"price",imageUrl,#"image",shipping,#"shipping_day", nil];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *cartList = [[defaults objectForKey:#"CART_ITEMS"] mutableCopy];
if(!cartList)
cartList = [[NSMutableArray alloc] init];
if([cartList indexOfObject:tempDictionary] == NSNotFound)
{
NSLog(#"add favorite");
[cartList addObject:tempDictionary];
[defaults setObject:cartList forKey:#"CART_ITEMS"];
[defaults synchronize];
[sender setTitle:#"Remove" forState:UIControlStateNormal];
}
else
{
NSLog(#"remove favorite");
[cartList removeObject:tempDictionary];
[defaults setObject:cartList forKey:#"CART_ITEMS"];
[defaults synchronize];
[sender setTitle:#"Add to cart" forState:UIControlStateNormal];
}
this is what I do everytime I want my favorite list from NSUserDefault
-(void)getCartList
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *cartList = [[defaults objectForKey:#"CART_ITEMS"] mutableCopy];
productListArr = [NSMutableArray arrayWithArray:cartList];
NSLog(#"cart list data == %#", cartList);
}