Table view cells lose their order - ios

Goal
I'm trying to create a table view like Instegram's home screen.
I've made a custom cell, I'm initialising it with data, the cell suppose to hold the "Post".
Logic
I save each cell in a NSMutableDictionary , the key is the index of the posts order and the value is the post it self.
Current Result
I scroll down, and everything is fine. The order you see is post1, post2, post3...post 8 but when I scroll up, everything mess up and the post order is post8, post6, post7, post8, post5... You get the point.
(Before asking here I tried doing it with small objects - a REGULAR ! (not custom) cell containing only strings.
for some reason it worked ! the order was perfect.)
Code
this is my UITableViewController - my "Home" screen "cellForRow" Method.
if we scroll up and the index of the Tableview is alrdy have been initialised, I pull the post form the dictionary.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *PC = #"PostCell";
PostCell *Pcell = [tableView dequeueReusableCellWithIdentifier:PC forIndexPath:indexPath];
NSString *key = [[NSString alloc] initWithFormat:#"%i", indexPath.section];
NSLog(#"Cell %i", indexPath.section);
// Checking if alrdy visted this indexpath.
if (![_allcells objectForKey:key]) {
[self setPostUserName:[[NSString alloc] initWithFormat:#"username: %i", indexPath.section]:Pcell];
// Saving a postcell I wont return, just to save in a dictionary.
// When we get here again it will get another pointer like that my object wont change.
PostCell* toSave = [[PostCell alloc] init];
// saving it with current post data.
[self copyPost:toSave :Pcell];
[_allcells setObject:toSave forKey:key];
}
else {
// Copying post daya
[self copyPost:Pcell :[_allcells objectForKey:key]];
}
NSLog(#"Cell %i Returning: %#", indexPath.section, Pcell.userName.text);
return Pcell;
}
// Check if it reached the end
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
float endScrolling = scrollView.contentOffset.y + scrollView.frame.size.height;
if (endScrolling >= scrollView.contentSize.height)
{
NSDictionary *temparr = [[NSDictionary alloc] initWithDictionary:_allcells];
[self.tableView reloadData];
_allcells = [[NSMutableDictionary alloc] initWithDictionary:temparr];
}
}
and this is my PostCell.h , so you can see the attributes.
#interface PostCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UIImageView *profilePic;
#property (strong, nonatomic) IBOutlet UILabel *userName;
#property (strong, nonatomic) IBOutlet UILabel *checkIn;
#property (strong, nonatomic) IBOutlet UILabel *uploadedAgo;
#property (strong, nonatomic) IBOutlet UIImageView *mainPic;
#property (strong, nonatomic) IBOutlet UILabel *likes;
#property (strong, nonatomic) IBOutlet UILabel *participants;
#end
By the way, if you got a project example that has a result similar to Instagram home screen it would be great if you can link me to it!

You shouldn't store references to the cells, since they are being reused by the tableview when they leave the screen. At the moment everything works fine for you while scrolling down the first time, because you create the cells new. On scrolling up, you get the stored reference which now points to one of the newly created cells, so things look messed up.
What you should do is just populating the reused cells with the right data and only create them if needed. Like:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *PC = #"PostCell";
PostCell *Pcell = (PostCell*)[tableView dequeueReusableCellWithIdentifier:PC forIndexPath:indexPath];
// feed the needed data to the cell
return Pcell;
}
Not sure why you are accessing only indexPath.section since usually you would populate the table with multiple cells per section, using indexPath.row.

Okay, I found out the mistake, Because I was first I was saving the id of each Post and than took it out of the dictionary it didn't work.
than I was trying to only save the attributes of the post by creating a "fake" postCell and saving the attribues of the original cell in the fake cell and than took it out of the array and made the cell copy ONLY the attributes of the cell I just took out and it didn't work.
why? because no matter what I was saving a POINTER ! to those fields !.
I've created a class which was ment to save my desired data that's the class I entered my dictionary.
now each time I dequeue a cell, I load it with the data of the index I'm at. :)
So nice to finally solve it and to learn something new, thanks for giving me leads !

A UITableView works best with an array. Also an array will stay in order as it is indexed, while dictionaries have no index, and thus will not retain order. Also separate cells of the same type, in this case PostCell, should not have different sections, but instead different rows. Use section to separate different categories of cells.
Another tip; NSMutableDictionary takes up more memory than an NSDictionary. Once you have set everything in your NSMutableDictionary, store it in an NSDictionary. If you want to modify it in the future, copy it back into an NSMutableDictionary, modify it, and then store it again as an NSDictionary.
#property (strong, nonatomic) NSDictionary *post;
// To create an NSDictionary
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"74 degrees" forKeyPath:#"weather"];
post = tempDict;
// To modify an NSDictionary
tempDict = [[NSMutableDictionary alloc] initWithDictionary:post];
[tempDict removeObjectForKey:#"weather"];
post = tempDict;
Then store it in an array.
#property (strong, nonatomic) NSArray *allPosts;
// NSMutableArray takes up more memory than NSArray
NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:allPosts];
[tempArray addObject:post];
allPosts = tempArray;
Finally, display it in your tableview.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *PC = #"PostCell";
PostCell *pCell = [tableView dequeueReusableCellWithIdentifier:PC];
if (!cell) {
pCcell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PC];
}
NSDictionary *currentPost = [allPosts objectAtIndex:indexPath.row];
// Instead of having post1, post2, post3 and so forth, each post is now in currentPost. If there are 10 posts, then this function will run 10 times. Just write the code as if you are handling one post, and the UITableView will automatically fill in the rest of the posts for you.
return cell;
}

Related

Change image on click in custom table cell made from nib

I have a table with custom cells that are made from a nib file. When a user clicks a cell it expands in height , thus simulating a dropdown. In the custom cell there is an imageView that has a dropDown image when the cell is not clicked. However when the cell is clicked it should change the image to a collapse image or arrow up image to show that the cell is open.
I am having a problem changing the image when the cell expands from arrow down to arrow up and vice versa. I would like assistance achieving this.
Here is my code :
ViewController.h
#interface ViewController : UIViewController <UITableViewDelegate,
UITableViewDataSource>
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property(nonatomic, strong) NSArray *items;
#property (nonatomic, assign) BOOL expandFlag;
#property (nonatomic, assign) NSIndexPath* selectedIndex;
ViewController.m
- (NSArray *) items
{
if (!_items) {
_items = [NSArray new];
}
return _items;
}
- (void)viewDidLoad {
[super viewDidLoad];
UINib *nib = [UINib nibWithNibName:#"CustomTableViewCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:#"cell"];
_items = #[
#{#"title":#"Simpson", #"short":#"Homer", #"long":#"Mr jhvjm,b;k t tyfy rctrc rtcf rvty rthvgh bb r5ertvyg hg r5 tyhg 6ruygj 8rutyj r6yiugg tygdtjhgfdt hg tvt gthgfgni7yjftgjhb ftgfh b yjh gtfjfyhh j jj j", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Simpson", #"short":#"Marge", #"long":#"Mrs bjyvhm uikn o utv jb k", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Simpson", #"short":#"Bart", #"long":#"Mr vubj cbjknuy iubyuvjh biubkj ", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Simpson", #"short":#"Lisa", #"long":#"Miss jbjvjbbiuvu yuvhj uby ", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Simpson", #"short":#"Maggie", #"long":#"Miss iubniyujh k iuuh ", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Flanders", #"short":#"Ned", #"long":#"Mr hbuyvj iybkj nui uhc n", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."}
];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) didExpandCell{
_expandFlag = !_expandFlag;
[self.tableView reloadRowsAtIndexPaths:#[_selectedIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.items.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSDictionary *item = _items[indexPath.row];
cell.titleImage.text = [item objectForKey:#"title"];
cell.longLabel.text = [item objectForKey:#"long"];
cell.shortLabel.text = [item objectForKey:#"image"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
_selectedIndex = indexPath;
[self didExpandCell];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (_expandFlag && _selectedIndex == indexPath) {
return 400;
}
return 200;
}
CustomeTableViewcell.h
#interface CustomTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *thumbImage;
#property (weak, nonatomic) IBOutlet UILabel *titleImage;
#property (weak, nonatomic) IBOutlet UILabel *shortLabel;
#property (weak, nonatomic) IBOutlet UILabel *longLabel;
#property (weak, nonatomic) IBOutlet UIImageView *dropDownImage;
CustomerTableViewCell.m
- (void)awakeFromNib {
[super awakeFromNib];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
You should check and change dropDownImage in cellForRowAtIndexPath method. Something likes the code below
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSDictionary *item = _items[indexPath.row];
cell.titleImage.text = [item objectForKey:#"title"];
cell.longLabel.text = [item objectForKey:#"long"];
cell.shortLabel.text = [item objectForKey:#"image"];
NSString *dropDownImageName = [indexPath isEqual:_selectedIndex] && _expandFlag ? #"ARROW_DOWN" : #"ARROW_UP";
cell.dropDownImage.image = [UIImage imageNamed:dropDownImageName];
return cell;
}
Change ARROW_UP and ARROW_DOWN with your image names.

UITableViewController: Objects properties deallocated

I'm using a UITableViewController to display a list of articles from a web service. Once the data is retrieved this delegate method is called:
-(void)itemsDownloaded:(NSArray *)items
{
// Set the items to the array
_feedItems = items;
// Reload the table view
[self.tableView reloadData];
}
I'm also using a custom cell so that the label's height varies, therefore displaying the whole of the article's title with the following code (followed this tutorial Table View Cells With Varying Row Heights):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = #"BasicCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
[self configureCell:cell forRowAtIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell isKindOfClass:[CustomTableViewCell class]])
{
CustomTableViewCell *textCell = (CustomTableViewCell *)cell;
Article *article_item = _feedItems[indexPath.row];
NSString *fulltitle = article_item.Title;
// fulltitle = article_item.Cat_Name; // testing category name
if (article_item.Subtitle != nil && article_item.Subtitle.length != 0) {
fulltitle = [fulltitle stringByAppendingString:#": "];
fulltitle = [fulltitle stringByAppendingString:article_item.Subtitle];
}
textCell.lineLabel.text = fulltitle;
textCell.lineLabel.numberOfLines = 0;
textCell.lineLabel.font = [UIFont fontWithName:#"Novecento wide" size:12.0f];
}
}
- (CustomTableViewCell *)prototypeCell
{
NSString *cellIdentifier = #"BasicCell";
if (!_prototypeCell)
{
_prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
}
return _prototypeCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
[self configureCell:self.prototypeCell forRowAtIndexPath:indexPath];
self.prototypeCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(self.prototypeCell.bounds));
[self.prototypeCell layoutIfNeeded];
CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height+1;
}
The first issue is that the method forRowAtIndexPath is being called twice instead of once. Therefore if the _feeditems has 10 objects, the method is called 20 times. The second time the method is called I'm getting two properties (ID and Cat_Name) of the Article object null since of deallocation:
*** -[CFString retain]: message sent to deallocated instance 0x9c8eea0
*** -[CFNumber respondsToSelector:]: message sent to deallocated instance 0x9c8e370
This fires an EXC_BAD_ACCESS when trying to display the category name.
I'm not sure what can be the problem exactly, I've tried removing the code to vary the height of the labels to see if that was causing this problem by using this code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Retrieve cell
NSString *cellIdentifier = #"BasicCell";
UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// Get article
Article *item = _feedItems[indexPath.row];
myCell.textLabel.text = item.Title;
return myCell;
}
The only difference was that the method was being called once meaning 10 times if _feeditems has 10 objects. But the Article's properties ID and Cat_Name were still being deallocated.
At the point of getting the data, all objects' properties in _feeditems are intact, nothing deallocated. I guess it's happening in cellForRowAtIndexPath or forRowAtIndexPath.
UPDATE
As suggested by #Ilya K. not calling configureCell:forRowAtIndexPath: from tableView:heightForRowAtIndexPath stopped the issue of having it being called twice. I've also tried having a property of feedItems. So far this was being set in the #interface of the Controller (TableViewController.m):
#interface TableViewController () {
HomeModel *_homeModel;
NSArray *_feedItems;
Article *_selectedArticle;
}
I've removed it from the interface and added it as a property (TableViewController.h):
#interface TableViewController : UITableViewController <HomeModelProtocol>
#property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;
#property (nonatomic, strong) CustomTableViewCell *prototypeCell;
#property(nonatomic) NSString *type;
#property(nonatomic) NSString *data;
#property(copy) NSArray *_feedItems;
#end
It's still giving deallocated messages though.
UPDATE 2
I've looked through the code using Instruments with a Zombie template (thanks to the answer of this question ViewController respondsToSelector: message sent to deallocated instance (CRASH)). This is the error I'm getting from Instruments:
Zombie Messaged
An Objective-C message was sent to a deallocated 'CFString (immutable)' object (zombie) at address: 0x10c64def0
All Release/Retain Event Types point to the following method, connectionDidFinishLoading, which is being used when the JSON data is retrieved from the web service and create Article objects for each article retrieved:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the articles
NSMutableArray *_articles = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
// Highlighted in blue
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:_downloadedData options:kNilOptions error:&error];
NSArray *fetchedArr = [json objectForKey:#"result"];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < fetchedArr.count; i++)
{
NSDictionary *jsonElement = fetchedArr[i];
// Create a new location object and set its props to JsonElement properties
Article *newArticle = [[Article alloc] init];
newArticle.ID = jsonElement[#"ID"];
newArticle.Title = jsonElement[#"Title"];
newArticle.Subtitle = jsonElement[#"Subtitle"];
newArticle.Content = jsonElement[#"Content"];
newArticle.ImageUrl = jsonElement[#"ImageUrl"];
newArticle.Author = jsonElement[#"Author"];
newArticle.PostId = jsonElement[#"PostId"];
newArticle.ArticleOrder = jsonElement[#"ArticleOrder"];
newArticle.Cat_Id = jsonElement[#"CategoryId"];
// Highlighted in yellow
newArticle.Cat_Name = jsonElement[#"CategoryName"];
// Add this article object to the articles array
// Highlighted in yellow
[_articles addObject:newArticle];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_articles];
}
}
I still can't figure out what is wrong though.
UPDATE 3
More testing on connectionDidFinishLoading I've removed the two properties that are being deallocated and no deallocated messages are shown. I don't know what's causing these two properties (ID and Cat_Name) to be deallocated, these are not being accessed from anywhere at this point.
You don't need to call to configureCell:forRowAtIndexPath: from tableView:heightForRowAtIndexPath: you should determine cell height using Article object with sizeWithAttributes:
Your prototypeCell function just creates unrelated empty cell of type CustomTableViewCell and there is no point of trying re-size it.
tableView:cellForRowAtIndexPath: called each time your tableview needs redraw, when you scroll for example. That means that your _feeditems array should be allocated and consistent to work with UITableView at any point of instance life time.
Also make sure you declare a property for _feeditems and assign data using this property.
Example:
#property (strong) NSArray *feeditems; or #property (copy) NSArray *feeditems;
in itemsDownloaded:
self.feeditems = items;
Finally solved the deallocated messages issue. While using Instruments with a Zombie template (using Instruments and Zombie template: ViewController respondsToSelector: message sent to deallocated instance (CRASH)) I found that this line:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:_downloadedData options:kNilOptions error:&error];
in the connectionDidFinishLoading method was causing this problem. I searched for NSJSONSerialization causing deallocation messages and I got the answer from this question Loading properties from JSON, getting "message sent to deallocated instance". The Article class had a few properties that were set to assign instead of strong:
#interface Article : NSObject
#property (nonatomic, assign) NSNumber *ID; // changed assign to strong
#property (nonatomic, strong) NSString *Title;
#property (nonatomic, strong) NSString *Subtitle;
#property (nonatomic, strong) NSString *Content;
#property (nonatomic, strong) NSString *ImageUrl;
#property (nonatomic, assign) NSNumber *PostId; // changed assign to strong
#property (nonatomic, strong) NSString *Author;
#property (nonatomic, assign) NSNumber *ArticleOrder; // changed assign to strong
#property (nonatomic, assign) NSNumber *Cat_Id; // changed assign to strong
#property (nonatomic, assign) NSString *Cat_Name; // changed assign to strong
#end
After changing the properties to strong, all deallocated messages stopped.
I know that this error seems to be very specific to each project and the cause of it may vary but in case someone has something similar, this is how I solved it.

UIPickerView reloadAllComponents doesn't get called

I have 2 table cells, based on what i have selected in my first cell, i have to refresh the second cell, when i click the second cell a container view with a picker is changed from hidden to unhidden state.
When I press the cell I have a method which gets called where after i get the new data I reload my picker, but that line of code doesn't get called, my picker isn't refreshed:
-(void)reloadData:(NSUInteger) path{
//NSUInteger path = (NSUInteger)self.parentVC.pozOras;
NSString *parcareFile = [[NSBundle mainBundle] pathForResource:#"Parcare"
ofType:#"plist"];
self.fisier = [NSArray arrayWithContentsOfFile:parcareFile];
////Log(#"reloadData:%#",self.fisier);
NSDictionary *infoOras = [self.fisier objectAtIndex:path];
// NSLog(#"reloadData:%#",infoOras);
NSLog(#"reloadData:%d",(NSInteger)path);
NSArray *zones = [infoOras valueForKey:#"Zone"];
self.zone = [zones valueForKey:#"name"];
NSLog(#"reloadData:%#",self.zone);
self.price = [zones valueForKey:#"price"];
NSLog(#"reloadData:%#",self.price);
self.time = [zones valueForKey:#"durationminutes"];
NSLog(#"reloadData:%#",self.time);
[self.listaCuZone reloadAllComponents];
}
All the data from the Output of NSLog is what is should be in the picker.
I have the property of the UIPickerView in the header file, everything seems to be in place. I really don't know why it doesn't get called.
#interface PickerZone : UIViewController<UIPickerViewDataSource,UIPickerViewDelegate>
#property (nonatomic, assign) FirstViewController *parentVC;
#property NSInteger zona;
#property NSUInteger path;
#property NSMutableArray *fisier;
#property NSMutableArray *zone, *price, *time;
#property (strong, nonatomic) IBOutlet UIPickerView *listaCuZone;
- (IBAction)doneButton:(id)sender;
- (void)reloadData:(NSUInteger)path;
#end
Here is where i call the method from:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.section == 0){
[self.listaZone viewForBaselineLayout].hidden = YES;
[self.listaOrase viewForBaselineLayout].hidden = NO;
}
else
{
PickerZone *pickerZone = [[PickerZone alloc]init];
[pickerZone reloadData:(NSUInteger)self.pozOras];
[pickerZone.listaCuZone reloadAllComponents];
[self.listaOrase viewForBaselineLayout].hidden = YES;
[self.listaZone viewForBaselineLayout].hidden = NO;
}
}
As you can see, i also try to reload the components here.
I have the delegate and the datasource also linked to the vc.
If i should post some more code please let me know, i really want to fix this.
Here is a screenshot of the storyboard: https://www.dropbox.com/s/4nkpz55zlcffh9w/Screenshot%202014-02-16%2019.31.24.png

Data is disappearing from UITableView

I am building an iOS app with a custom tab bar at the top. When i click on the home icon, I want it to show a tableview directly below the tab bar. Currently my code does just that, however the data doesnt show correctly. If I limit my Cells to 4 or less (in the numberFoRowsInSection), the data will show, if i have like say 15 cells, the data shows for a split second and then it disappears. I have been looking at tutorials all over the place and everything seems to be correct, the data will show correctly in a stand alone view(like i created a similar to a singleview application in the story board and made that the initial view). I dont know where i am wrong. Below is my code in implementation file of the tableviewContoller class:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 4;//this works... but change to 15 it doesnt work
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
PrayerCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CustomCell"];
if (cell == nil) {
NSLog(#"cell is Nil"); //never hits this
cell = [[PrayerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CustomCell"];
}
//the data showing is the correct data that i want to see
cell.dName.text = [[news objectAtIndex:indexPath.row] objectForKey:#"displayname"];
cell.priority.text = [[news objectAtIndex:indexPath.row]objectForKey:#"priority"];
cell.dateTime.text = [[news objectAtIndex:indexPath.row] objectForKey:#"datetime"];
cell.numPraying.text = #"2 praying";
cell.requestPreview.text = [[news objectAtIndex:indexPath.row] objectForKey:#"request"];
NSLog(#"created cell") //verify cell was made
return cell;
}
Here is my PrayerCell.H file
#interface PrayerCell : UITableViewCell
#property (weak, nonatomic)IBOutlet UILabel *requestPreview;
#property (weak, nonatomic)IBOutlet UILabel *dName;
#property (weak, nonatomic)IBOutlet UILabel *dateTime;
#property (weak, nonatomic)IBOutlet UILabel *numPraying;
#property (weak, nonatomic)IBOutlet UILabel *priority;
#end
I made no Changes to the prayerCell.M file
if you need me to post any other code blocks/screenshots please let me know.
The cell should not be an ivar, it should be a local variable. You also need to dequeue the cell in your tableView:cellForRowAtIndexPath: method:
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:#"CustomCell"];

modify an nsmutablearray in another class

I have a NSMutableArray of seven bools in managerViewController, these represent days of the week when a shop is open. I am running out of space in this view and most of the time the user will be happy with the default setting of open all hours.
the user needs to be able to change them to suit their business needs, my current approach to this is to have a uitableview of seven rows all of which have switches in them. where I am stuck is how to the actions of in uitableview modify the original nsmuntable array in the manageViewController class.
I am new to iOS, but I have built the UITableView and all the other bits, it is just accessing the NSMutableArray I am stuck on.
Use replaceObjectAtIndex:withObject: or, with the new objective-c literals it's much easier:
NSMutableArray *myArray = [NSMutableArray array];
myArray[0] = #(YES); // the same as: [myArray addObject:[NSNumber numberWithBool:YES]];
myArray[0] = #(NO); // the same as: [myArray replaceObjectAtIndex:0 withObject:[NSNumber numberWithBool:YES]];
Define a delegate to your table view controller, sayTableViewControllerDelegate. Add a delegate property to your table view controller
#property (weak, nonatomic) id delegate;
Make your ManagerViewController conform to the delegate protocol, and upon showing TableViewController, set its delegate to be your ManagerViewController instance.
Add a method in the delegate to inform the action on a day, for example:
- (void) didModifyDay:(NSInteger)dayNumber;
or
- (void) didChangeDay:(NSInteger)dayNumber toState:(BOOL)selected;
When table view is loading in the
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
make sure to check initial values for all of the switch and set values from your data source (the mutable array). For easily handle the situation use a custom and put its object in the array.
#interface Days : NSObject
#property (nonatomic, retain) NSString *day;
#property (nonatomic, assign) BOOL isOpen;
#end
i.e.
for(int ii = 0; ii < 7; ii++ ){
Days *days = [[Days alloc] initWithDay:ii isOpen:YES];
[array addObject:days];
[days release];
}
Assume that you have a custom UITableViewCell which have a property set to the switch.
i am using cell.switch for example.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"reusableCells";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if(cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
Days *days = [array objectAtIndex:indexPath.row];
cell.textLabel.text = days.day;
[cell.switch setOn:days.isOpen animated:YES];
return cell;
}
and this will handle your switch.
now assume you toggle the switch on/off when press the table cell so handle the didSelectRowAtIndexPath method of the tableview delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
Days *days = [array objectAtIndex:indexPath.row];
days.isOpen != days.isOpen;
[cell.switch setOn:days.isOpen animated:YES];
}
That's all. you will get the switch toggle on/off and the will be manipulated from the array.
You can use the app delegate class of your application to access the NSMutableArray.
In the app delegate class create the property for the class in which that NSMutableArray is present for e.g let say class name is TestController.
//then in .h file of Appdelegate
#import TestController.h
//in the interface
TestController *objTest;
//declare the property
#property (nonatomic, strong) TestController *objTest;
//then in the .m file of app delegate synthesize the object
#synthesize objTest;
Now in the similar way declare the property for NSMutableArray in the TestController
Create the share instance of the app delegate class where you want to access the NSMutable array object(say arr1) as below
AppDelegate *objAppDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
You can access that array as "objAppDelegate.objTest.arr1"
Or
You can create the share instance in the view controller class
//in the .h of view controller
+ (id)sharedInstance;
//in the .m of view controller
+ (id)sharedInstance
{
// structure used to test whether the block has completed or not
static dispatch_once_t p = 0;
// initialize sharedObject as nil (first call only)
__strong static id _sharedObject = nil;
// executes a block object once and only once for the lifetime of an application
dispatch_once(&p, ^{
_sharedObject = [[self alloc] init];
});
// returns the same object each time
return _sharedObject;
}
Then in the application where you fill the array use,
TestViewController *objTest=[TestViewController sharedInstance];
objTest.arr1=[[NSMutableArray alloc]initWithObjects:#"1",#"1",#"1",#"1", nil];
And in the table view controller you can access it as below
TestViewController *objTest=[TestViewController sharedInstance];
objTest.arr1 will be the resulted array.

Resources