Saving NSUserDefault data and showing it in table view - ios

I am trying to save my data by NSUserDefaults and view it in table view. I have already set four texts data to an array (dataArray) so I can view it in the table view. but I couldn't load the data to the table view. So am I missing something?
Thanks in advance.
-(IBAction)save{
NSUserDefaults *add1 = [NSUserDefaults standardUserDefaults];
[add1 setObject:txt1 forKey:#"txt1"];
[add1 setObject:txt2 forKey:#"txt2"];
[add1 setObject:txt3 forKey:#"txt3"];
[add1 setObject:txt4 forKey:#"txt4"];
[add1 synchronize];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
self.dataArray = [NSArray arrayWithObjects:[prefs objectForKey:#"txt1"], [prefs objectForKey:#"txt2"], [prefs objectForKey:#"txt3"],[prefs objectForKey:#"txt4"] nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// Set up the number of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [dataArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"Cell";
UITableView *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
}

You have to call [yourUserDefaultObject synchronize]; to save the state of the NSUserDefaults, but you don't really need to create 4 objects of NSUserDefaults, you can just create it one time and then call setObject:forKey: on the same instance and then synchronize.
Then just set cell.textLabel.text=string; to set the label of the cell in the cellForRowAtIndexPath callback.

First syncronize nsuserdefaults and
You need to alloc the tableviewcell and assign the text to the text label
Add following code in your cellForRowAtindexpath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [dataArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text=string;
return cell;
}

Dude add following line because you need to add test somewhere in cell. So that can display on tablviewcell. If possible than please first make array than save whole array in NSUserDefaults by that way you save your time and that's better way to do coding.
cell.textLabel.text=string;
Edited>>>
UILabel *label;
label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 50, 40)];
label.text = string;
// or
label.text = #"Hi I am here..";
label.backgroundColor = [UIColor greenColor];
label.textColor = [UIColor whiteColor];
[cell addSubview:label];

Related

In UItableview, when I scroll table values are miss placing(values selecting from picker)

Here I am trying to do dynamic UITableViewCell with UIPickerView.
Step 1:
In Custom cell, I took 1 label and 1 UITextField.
Step 2:
used downpickerview library for data displaying and data fetching.
Step 3:
using below code I can able to select data, but after that, if I scroll UITableView data will be miss placing.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"Cell";
customCell *cell1=[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell1 == nil)
{
cell1 = [[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
cell1.productTitleLabel.text =[arrProductTitle objectAtIndex:indexPath.row];
self.downPicker = [[DownPicker alloc] initWithTextField:cell1.productvalueTextfield withData:arrProductVal];
[self.downPicker addTarget:self action:#selector(measurementSelected:) forControlEvents:UIControlEventValueChanged];
[cell1.contentView addSubview:self.downPicker];
return cell1;
}
Please help me on this.
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = #"DETAILS";
_dict = [[NSMutableDictionary alloc]init];
arrProductTitle = [[NSMutableArray alloc]initWithObjects:#"title0",#"title1",#"title2",#"title3",#"title4",#"title5",#"title6",#"title7",#"title8",#"title9",#"title10",#"title11",#"title12",#"title13",#"title14",#"title15", nil];
arrProductVal = [[NSMutableArray alloc]initWithObjects:#"0",#"1",#"2",#"3",#"4",#"5",nil];}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return arrProductTitle.count-1;}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *MyIdentifier = #"Cell";
customCell *cell1=[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell1 == nil)
{
cell1 = [[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
cell1.productTitleLabel.text =[arrProductTitle objectAtIndex:indexPath.row];
NSLog(#"%#",_dict);
NSLog(#"%#",[NSString stringWithFormat:#"%ld",(long)indexPath.row]);
if (_dict[[NSString stringWithFormat:#"%ld",(long)indexPath.row]]) {
cell1.productvalueTextfield.text =[_dict valueForKey:[NSString stringWithFormat:#"%ld",(long)indexPath.row]];
}
else {
cell1.productvalueTextfield.text = #"";
self.downPicker = [[DownPicker alloc] initWithTextField:cell1.productvalueTextfield withData:arrProductVal];
self.downPicker.tag = indexPath.row;
[self.downPicker addTarget:self action:#selector(measurementSelected:) forControlEvents:UIControlEventValueChanged];
[cell1.contentView addSubview:self.downPicker];
}
return cell1;}
-(void)measurementSelected:(id)dp {
NSString* selectedValue = [dp text];
NSString* selectedIndex = [NSString stringWithFormat:#"%ld",(long)[dp tag]];
[_dict setValue:[dp text] forKey:selectedIndex];
NSLog(#"_dict: %#",_dict);
NSLog(#"SELECTED TAG:::::::%ld",[dp tag]);
NSLog(#"SELECTED VALUE:::::::%#",selectedValue);
NSLog(#"SELECTED INDEX VALUEEEEEEEEEEE:::::::%ld",[dp selectedIndex]);}
https://github.com/gvniosdev/Dynamic-UItableview-with-Picker-Selection
UITableViewCell values are misplacing because you haven't set the data for other cells, You need to store the values in an array and just update the values from there and it will work. :)
Something is not right with your code:
cell1.productTitleLabel.text =[arrProductTitle objectAtIndex:indexPath.row];
self.downPicker = [[DownPicker alloc] initWithTextField:cell1.productvalueTextfield withData:arrProductVal];
[self.downPicker addTarget:self action:#selector(measurementSelected:) forControlEvents:UIControlEventValueChanged];
[cell1.contentView addSubview:self.downPicker];
Bear in mind that in iOS, a tableView will reuse its cells. So when you scroll your UITableView, it will reuse the old cells which were created before, and
[cell1.contentView addSubview:self.downPicker]; Will be executed everytime a cell is reused, as a result, you will end up having many downPicker objects in one cell.

How to save text fields in a custom tableview cell

Question is in the title ^^. How do you go about saving say 2 textFields in a custom tableView cell. Pretend the reuse identifier doesn't exist (however is someone could show me how to get around that then that would be awesome). Thanks for anyone that can help.
In your custom UITableViewCell class you can add textfields from an array of textfields.
ie, in the viewDidLoad you can insert two textfields of tag 110 and 111 in an array.
-(void)viewDidLoad
{
arryTextfields = [NSMUtableArray alloc]init];
for(int i=0;i<2;i++)
{
UITextField * textField = [[UITextField alloc]init];
NSMutableDictionary * dic =[NSMutableDictionary alloc]init]
[dic setObject:textField forKey:[NSString stringWithFormat:#"11%d",i]];
[arryTextfields addObject:dic];
[textField release];
[dic release];
}
}
In your tableview delegate "cellForRowAtIndexPath".
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
YourCustomTableviewCell * cell = [[YourCustomTableviewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UITextField * textfield1 = [[cell.arryTextfields objectAtIndex:indexPath.row]objectForKey:#"110"];
UITextField * textfield2 = [[cell.arryTextfields objectAtIndex:indexPath.row]objectForKey:#"111"];
return cell;
}

Issue with running through NSArray - Obj C

I have an NSDictionary objectreturned from my server. I am using it to populate information on a UITableViewController. My issue is that when I am processing each object returned, it seems to duplicate, lets say I get 2 objects returned. It will make 2 table cells but with only the first object's data. So lets say the title section from both objects is "yes" and "no". It would populate the list with the first object title so it would show, yes and yes.
Here is what happens:
Controller is loaded:
- (void)viewDidLoad
{
[super viewDidLoad];
// MAKE REQuEST TO SERVER
[self makeRequests];
}
runs the request from server which stores information as follow:
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:returnData //1
options:kNilOptions
error:&error];
self.googlePlacesArrayFromAFNetworking = [json objectForKey:#"requested_data"];
[self.tableView reloadData];
than the cellForRowAtIndexPath runs:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"timelineCell";
FBGTimelineCell *cell = (FBGTimelineCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[FBGTimelineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.usernameLabel.text = [_googlePlacesArrayFromAFNetworking[indexPath.row] objectForKey:#"name"]; <!-- here is where the title example I was talking about happens
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell initTimelineCell];
}
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:#"%d.jpg", indexPath.row]];
cell.photoView.image = img;
return cell;
}
Here is my googlePlacesArr...
#property (strong, nonatomic) NSArray *googlePlacesArrayFromAFNetworking;
Here is my numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.googlePlacesArrayFromAFNetworking count];
}
Suggestions thoughts? Let me know if you need anything else.
UPDATE:
Also I think its important to note I am using this:
https://github.com/Seitk/FB-Gallery
As a base for populating my returned data.
This usually happens when the cell gets recycled if your tableView:cellForRowAtIndexPath: method fails to set some of the members of recycled objects.
That is precisely what happens in your code: when the cell is recycled, you never set its usernameLabel.text, so the recycled value may be shown multiple times.
You should move the code that sets up cell's properties outside of the if statement to fix this problem:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"timelineCell";
FBGTimelineCell *cell = (FBGTimelineCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[FBGTimelineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell initTimelineCell];
}
// This line is moved from the "if" statement
cell.usernameLabel.text = [_googlePlacesArrayFromAFNetworking[indexPath.row] objectForKey:#"name"];
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:#"%d.jpg", indexPath.row]];
cell.photoView.image = img;
return cell;
}
Try this:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
/* /////// Custom code ////// */
cell.usernameLabel.text = [_googlePlacesArrayFromAFNetworking[indexPath.row] objectForKey:#"your_key_name"];
}

Custom Check mark for selected Row

I am using a Custom image for checkmark - 'iphone-checkMark#2x.png' in a `UITableViewCell, but it's displaying everywhere in the cell. Can anyone suggest how to make it display only for the single selected cell?
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10, 300, 30)];
[cell.contentView addSubview:label];
label.text = [tableArr objectAtIndex:indexPath.row];
label.font = [UIFont fontWithName:#"Whitney-Light" size:20.0];
label.tag = 1;
UIImageView *checkmark = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"iphone-checkMark#2x.png"]];
cell.accessoryView = checkmark;
return cell;
}
Less code is better:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
cell.textLabel.text = [tableArr objectAtIndex:indexPath.row];
cell.textLabel = [UIFont fontWithName:#"Whitney-Light" size:20.0];
return cell;
}
UPDATE:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
lastIndexPath = indexPath;
[tableView reloadData];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([lastIndexPath isEqual:indexPath]) {
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"iphone-checkMark.png"]];
} else {
cell.accessoryView = nil;
}
}
UPDATE 2:
Write
//dont forget check for nil
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:lastIndexPath forKey:#"lastIndexPath"];
[defaults synchronize];
Read
NSIndexPath *lastPath = [defaults valueForKey:#"lastIndexPath"];
One way to achieve what you are trying to do is to use a button and set the background image as your checkbox. This button will be your accessoryView. Monitor the touch event on the button and display the boolean accordingly. The sample project in the following link will provide all the code you need to implement this. https://developer.apple.com/library/ios/#samplecode/Accessory/Introduction/Intro.html

Cannot seem to pass an array to uitableview xcode

I am trying to display the contents of an array onto a uitableview. It works fine if I assign the values individually but when I try to display them from an array xcode exits with nothing in the debugging report except (lldb). It compiles and runs great until I go to the page with the tableview. I've looked up the error and it seems to pertain to memory allocation but I am unable to manually release anything due to having to have ARC enabled for some JSON classes to operate. Can anyone take a look and see what possibly might be the issue.
- (void)viewDidLoad
{
[super viewDidLoad];
theArray = [[NSArray alloc] initWithObjects:#"1","2","3","4",nil];
// Do any additional setup after loading the view.
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [theArray count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Set up the cell...
self.recentSearchesTable.backgroundColor =[UIColor clearColor];
self.recentSearchesTable.separatorColor = [UIColor clearColor];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15];
cell.textLabel.text = [theArray objectAtIndex:indexPath.row];
cell.contentView.backgroundColor = [UIColor clearColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// open a alert with an OK and cancel button
NSString *alertString = [NSString stringWithFormat:#"Clicked on row #%d", [indexPath row]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertString message:#"" delegate:self cancelButtonTitle:#"Done" otherButtonTitles:nil];
[alert show];
}
In viewDidLoad your array contains non-object items, change it too:
theArray = [[NSArray alloc] initWithObjects:#"1",#"2",#"3",#"4",nil];
Note the # before each item in the array, indicating that they're NSString literals (and not c strings).
You did two mistake here first you need to initialize array in this way.
theArray = [[NSArray alloc] initWithObjects:#"1",#"2",#"3",#"4",nil];
and another mistake is you need to initialize cell when it is nil
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if you want whole code then like this way you need to implement.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Set up the cell...
cell.textLabel.text = [theArray objectAtIndex:indexPath.row];
cell.contentView.backgroundColor = [UIColor clearColor];
return cell;
}
First of all you do not need to disable ARC for your project due to an external class.You can exclude these classes by setting -fno-objc-arc flag.
Back to your answer
You should alloc a new cell if it can be reeused from a previous one.You should alloc you new cell if dequeueReusableCellWithIdentifier:CellIdentifier does not return a cell.
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Cellidentifier] autorelease];
}
Apart from that when you init your datasource array in viewDidLoad you need to add # before each element to indicate NSString.

Resources