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.
Related
I have a NSManaged Object that contains several string fields, like :
#interface myObject : NSManagedObject
#property (nonatomic, copy) NSString * name0;
#property (nonatomic, copy) NSString * name1;
#property (nonatomic, copy) NSString * name2;
I have a table view controller that displays the properties of this object and when someones clicks on a cell, it calls a second view controller (EditTableViewController below) that will allow to modify this particular cell. I would like to pass this second controller the NSString* it needs to modify (depending on the cell clicked).
Therefore I tried something like this for the second controller :
#interface EditTableViewController : UITableViewController
#property (nonatomic) NSString *value;
and in the implementation part I have (among others) :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
EditPropertyCell *cell = [tableView dequeueReusableCellWithIdentifier:#"EditPropertyCell"];
cell.valueTextField.text = self.value;
cell.valueTextField.delegate = self;
[cell.valueTextField becomeFirstResponder];
[cell.valueTextField setReturnKeyType:UIReturnKeyDone];
return cell;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
self.value = textField.text;
[self.navigationController popViewControllerAnimated:TRUE];
return YES;
}
The first controller owns a reference to an object of type myObject
#interface myObjectDetailTableViewController : UITableViewController
#property (nonatomic, strong) myObject * myObject;
and calls this second controller through :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
EditTableViewController *etvc = [[EditTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
if ([indexPath row] ==0) {
etvc.value = self.myObject.name0;
}
if ([indexPath row] ==1) {
etvc.value = self.myObject.name1;
}
if ([indexPath row] ==2) {
etvc.value = self.myObject.name2;
}
[self.navigationController pushViewController:etvc
animated:YES];
}
The problem it that it doesn't work, i.e. when I am in the EditTableViewController I can correctly see the value I want to modify (e.g. name0) but then if I modify it is not saved. I guess the NSString* has been copied somewhere but I can't figure out where. I wonder whether it has do with NSManagedObject ?
Anyway, maybe the way I am trying to do this is completely inappropriate in which case I would also be happy to know what would be the best approach to do it
(in particular, later on I would like ideally to be able to also set fields that were set to nil that way).
You can't just pass the string, because you need to tell the managed object that the string is changing and you do that by calling the managed object setter method for that property.
A better option is to pass both the managed object and the string which is the key that should be changed. Your controller can then use the key to get the existing value to display and set the value for that key to update the managed object (which then needs to be saved to store the update).
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;
}
This has been driving me crazy and not really sure whats going on. I have a UITableView and I'm populating the content of the UITableViewCells like so
- (UITableViewCell *)tableView:(UITableView *)a_tableView cellForRowAtIndexPath:(NSIndexPath *)a_indexPath
{
NewsItemCell * cell = (NewsItemCell *)[a_tableView dequeueReusableCellWithIdentifier:#"NewsItemCell"];
if(cell == nil)
{
cell = [[[NewsItemCell alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)] autorelease];
}
if(!m_isLoading)
{
NewsFeed * feed = [NewsFeed sharedNewsFeed];
NewsEntry * entry = [[feed feedEntries] objectAtIndex:[a_indexPath row]];
[cell setNewsEntry:entry];
}
else
{
if([a_indexPath row] < [m_visibleCells count])
{
return [m_visibleCells objectAtIndex:[a_indexPath row]];
}
}
return cell;
}
The line that contains [cell setNewsEntry:entry] takes the NewsEntry object and sets the cells textLabel.text to a string contained in entry. This works fine in iOS 6 but in iOS 7 the labels aren't showing the text.
- (void)setNewsEntry:(NewsEntry *)a_newsEntry
{
self.textLabel.text = a_newsEntry.title;
self.detailTextLabel.text = a_newsEntry.summary;
self.imageView.image = [self getIconForFeedType:[a_newsEntry feedType]];
}
I've done some poking around and in setNewsEntry and if I set self.textLabel.text to a string literal e.g. #"hello" then it works fine. I've also don't a lot of NSLogs inside of setNewsEntry to make sure that a_newsEntry actually has a valid title and summary properties, it does but for some reason the textLabel doesn't seem to be retaining them.
At first I was thinking that this was some memory issue with NewsEntry object but it doesn't make sense to me why this would be the case in iOS 7 and not iOS 6. Shouldn't the textLabel.text property retain the NSString that it gets set to?
If anyone has any ideas as to why this is happening please let me know and I can provide answers to any questions you have.
Thank you.
EDIT: NewsEntry Interface
#interface NewsEntry : NSObject
{
NSString * m_title;
NSString * m_summary;
NSString * m_published;
NSString * m_updated;
NSString * m_link;
int m_feedType;
}
#property (nonatomic, readonly) NSString * title;
#property (nonatomic, readonly) NSString * summary;
#property (nonatomic, readonly) NSString * published;
#property (nonatomic, readonly) NSString * updated;
#property (nonatomic, readonly) NSString * link;
#property (nonatomic, readonly) int feedType;
- (NSDictionary *)properties;
- (NewsEntry *)initWithProperties:(NSDictionary *)a_properties;
- (NSComparisonResult)compareEntry:(NewsEntry *)entry;
#end
Where you able to resolve it?
I have a similar issue where the detailTextLabel does not get updated on iOS7 whereas it works fine on iOS6. In my case, if I present another view on top and than go back to the tableview, I see the label updated already.
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.
I searched extensively for delegation tutorials, but could not get it to work. Here is the story and the code.
DetailViewController has a UITextField and a UIButton. When you press the button you get to another PricelistViewController with a simple sectioned table. Tapping a row in that table should return the text from the row's title to the first view and insert it into the text field. But it doesn't. Here is the code:
PricelistViewController.h (the second view):
#class PricelistViewController;
#protocol PricelistViewControllerDelegate <NSObject>
#required
//- (void)theSaveButtonOnThePriceListWasTapped:(PricelistViewController *)controller didUpdateValue:(NSString *)value;
- (void)theSaveButtonOnThePriceListWasTapped:(NSString *)value;
#end
#interface PricelistViewController : UITableViewController
#property (nonatomic, weak) id <PricelistViewControllerDelegate> delegate;
#property (retain, nonatomic) NSMutableArray * listOfSections;
#end
PricelistViewController.m
#synthesize delegate;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dictionary = [listOfSections objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"ProductSections"];
NSString *selectedProduct = [array objectAtIndex:indexPath.row];
[self.delegate theSaveButtonOnThePriceListWasTapped:[NSString stringWithFormat:#"%#", selectedProduct]];
[self.navigationController popViewControllerAnimated:YES];
}
This is the code in DetailViewController.h (the first view with a text field and the button):
#import "PricelistViewController.h"
#interface DetailViewController : UIViewController <UITextFieldDelegate, PricelistViewControllerDelegate>
DetailViewController.m (this I how I am trying to change the text in the field):
- (void)theSaveButtonOnThePriceListWasTapped:(NSString *)value
{
NSLog(#"Text, sent here: %#", value);
NSLog(#"Text was sent here.");
self.detailDescriptionLabel.text = value;
}
detailDescriptionLabel is the UITextField for the text to display.
Can somebody check the code and help? I work on this matter two days with no luck!
Firstly why are you forward referencing (#class) your class in the header file of the PriceListViewController? This isn't needed.
Secondly are you using ARC, if you are your array property should be of type nonatomic, strong. If you're not your delegate property should be nonatomic, assign. You seem to be mixing your terminology
Also where and how are you initialising your array?
I figured it out.
In the PricelistViewController.m I changed the way I call the method (added If statement):
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dictionary = [listOfSections objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"ProductSections"];
NSString *selectedProduct = [array objectAtIndex:indexPath.row];
if (delegatePrice && [delegatePrice respondsToSelector:#selector(theSaveButtonOnThePriceListWasTapped:didUpdateValue:)])
{
[delegatePrice theSaveButtonOnThePriceListWasTapped:self didUpdateValue:selectedProduct];
}
AND THE MOST IMPORTANT: I refused to use the Storyboard and instead made a old good .xib file for my PricelistViewController view and it worked right away!