Passing Data from Dynamic tableView to Static TableView - iphone

Hi Let me try to clarify my issue. I have two TableViews, one is static and the other is dynamic. The static= RootVC and Dynamic=FirstVC. In FirstVC i have data that I want to select,save and pass the saved data to a UILabel in RootVC. 1)When I run my App data is selected however it is not saved or passed to my rooVC. I was using delegates and was advice not to use "delegate" but use "Blocks". But still i'm facing the same issue. Here is my code:
in rootVC.h
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController
{
NSString *getRepeatLabel;
}
#property (strong, nonatomic) IBOutlet UILabel *repeatLabel;
#property (strong, nonatomic) IBOutlet UILabel *repeatDetail;
#property (nonatomic,strong) NSString *getRepeatLabel;
#end
in my rootVC.m
#import "RootViewController.h"
#interface RootViewController ()
#end
#implementation RootViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_repeatLabel.text = #"Repeat";
_repeatDetail.text = getRepeatLabel;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController *destinationController = segue.destinationViewController;
if( [destinationController isKindOfClass:[FirstViewController class]] )
{
[(FirstViewController *)destinationController setCompletionBlock:^(NSString *getRepeatLabel;)
{
// do something here with your string // maybe you must reload your table // it depends on where your returning data needs to display <--------Not sure what to do here
// NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
// NSArray*days = [dateFormatter shortWeekdaySymbols]; <------Here I would like when data is selected to show days in short symbol
NSLog (#"The selected day/s is %#", getRepeatLabel); <---nothing displaying on console
}];
}
}
#end
in FirstVC.h
#import <UIKit/UIKit.h>
#import "RootViewController.h"
typedef void(^WeekdayCompletionBlock)(NSString *dayName);
#interface FirstViewController : UITableViewController
{
NSString *dayName;
}
#property (nonatomic, strong) WeekdayCompletionBlock completionBlock;
#property (nonatomic,strong) NSString *dayName;
- (IBAction)save:(id)sender;
#end
in FirstVC.m
#import "FirstViewController.h"
#import "RootViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize completionBlock;
#synthesize dayName;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Initialize table data
completionBlock = [NSArray arrayWithObjects:#"Sunday", #"Monday", #"Tuesday", #"Wednesday", #"Thursday", #"Friday", #"Saturday", nil];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [completionBlock count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"RepeatCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [completionBlock objectAtIndex:indexPath.row];
return cell;
}
// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSLog (#"The selected day/s is %#", [completionBlock objectAtIndex:indexPath.row]);
_getRepeatLabel = completionBlock; //<-----------string from RootVC gives error "undeclared _getRepeatLabel"
}
- (IBAction)save:(id)sender
{
NSUserDefaults *myNewWeekString = [NSUserDefaults standardUserDefaults];
[myNewWeekString setObject:completionBlock forKey:#"%#"];
[myNewWeekString synchronize];
self.completionBlock(myNewDayOfWeekString) <------error myNewDayOfWeekString undeclared and if i declare it here it complains about incompatibility
}
#end

Your code is a little bit wrong. I think you don't really understand block.
You want to pass more than string so the best way to do that is via array. Change block definition to accept array instead of string:
typedef void(^WeekdayCompletionBlock)(NSArray *dayName);
Change declaration of your property in FirstVC.h to:
#property (nonatomic, copy) NSArray *completionBlock; //This is your array, you use it as data source, It's not a block
//Add your block property
// This is your block property you will use it to pass the data between view controllers
#property (copy) WeekdayCompletionBlock returnBlock;
//Add property to keep your selected days
#property (nonatomic, strong) NSMutableArray *returnArray;
Add this line to viewDidLoad method:
self.returnArray = [[NSMutableArray alloc] init];
Change your didSelectRowAtIndexPath method in FirstVC.m to:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
cell.accessoryType = UITableViewCellAccessoryNone;
//remove data from array
[self.returnArray removeObject:[completionBlock objectAtIndex:indexPath.row]];
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
//add data to array
[self.returnArray addObject:[completionBlock objectAtIndex:indexPath.row]];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
In your save: method call block and pass value to rootVC replace line:
self.completionBlock(myNewDayOfWeekString);
with:
if (self.returnBlock)
{
self.returnBlock(self.returnArray);
}
[self.navigationController popViewControllerAnimated:YES];
The last change left to do is set up ablok in your rootVC.m file. Replace line:
[(FirstViewController *)destinationController setCompletionBlock:
with (nsstring needs to be replaced with nsarray - you pass array with all of the selected data)
[(FirstViewController *)destinationController setCompletionBlock:^(NSArray *getRepeatLabel)
You set up block not NSArray.
I don't know what are you trying to do here:
[myNewWeekString setObject:completionBlock forKey:#"%#"];
You are using %# as a key. It should be text for example #"MY_KEY_FOR_ACCESING_DAYSOFWEEK". You are saving completionBlock it's all of your days if you want to save just selected days replace it with self.returnArray.
Hope this help.

Related

Accessing text from property from another class

I have tableview with the cells and every cell pushes detailViewController. I want to assign text of the cell to a textLabel in detailViewController.
.h class of masterView
#property (strong,nonatomic) NSString *selectedCellText;
.m class of masterView
#synthesize selectedCellText = _selectedCellText;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.selectedCellText = [[[tableView cellForRowAtIndexPath:indexPath] textLabel] text];
NSLog(#"%#",self.selectedCellText);
}
Here NSLog prints name of the cell
.h of detailViewController
#property (nonatomic, copy) listOfTricksViewController *aReference;
.m of detailViewController
#synthesize aReference = _aReference;
- (void)viewDidLoad
{
[super viewDidLoad];
self.detailViewName.text = self.aReference.selectedCellText;
NSLog(#"%#",self.aReference.selectedCellText);
}
Here NSLog prints null.
Modify your method prepareForSegue like this :
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:#"detailTrick"])
{
DetailViewController *detailViewController = (DetailViewController *)segue.
NSString *object = nil;
NSIndexPath *indexPath = nil;
indexPath = [self.tableView indexPathForSelectedRow];
// Pass data
detailViewController.aString = self.cellObjects[indexPath.row];
}
}
You need to call your DetailViewController and forward the data to this controller (supposing here you have a #property aString in your header of DetailViewController)
.h of detailViewController
#property (nonatomic, strong) NSString *aString;
.m of detailViewController
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.detailViewName.text = self.aString;
NSLog(#"%#",self.aString);
}

Master Detail Application - Static Table in Detail View

I'm trying to code an app in Xcode 4, with storyboarding. It's a master detail application, and it all worked fine, with the table and the detail view. But in my detail view, I would like to have a static table to display the data. In a grouped table style way, with the "key" on the left and "value" on the right, if that's a way to put it... So, it's all working fine until I put a table into my UIView. Apparently you have to put it in a UITableView for it to work, so I deleted the UIView that Xcode made for me and put in a UITableView in its place. I set it up EXACTLY the same (I think) with the identifier, title etc... and then connect the table cells up with outlets and what not. But now when I enter the view, I just get an empty table (well, not empty, just all the rows say "Detail" in rather than the actual data I want). I don't see why! D: I even changed DetailViewController.h to say "UITableViewController" as well! No avail... :( Could someone please enlighten me as to what I'm doing wrong! I bet it's really simple... :L Here's my code
MasterViewController.h
#import <UIKit/UIKit.h>
#class DetailViewController;
#interface MasterViewController : UITableViewController
#property (strong, nonatomic) DetailViewController *detailViewController;
#property (strong) NSMutableArray *verbs;
#end
MasterViewController.m
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "VerbData.h"
#interface MasterViewController () {
NSMutableArray *_objects;
}
#end
#implementation MasterViewController
#synthesize verbs = _verbs;
- (void)awakeFromNib
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
}
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.detailViewController = (DetailViewController *) [[self.splitViewController.viewControllers lastObject] topViewController];
self.title = #"Verbs";
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _verbs.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"VerbCell"];
VerbData *verb = [self.verbs objectAtIndex:indexPath.row];
cell.textLabel.text = verb.infinitive;
cell.detailTextLabel.text = verb.english;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
VerbData *object = [self.verbs objectAtIndex:indexPath.row];
self.detailViewController.detailItem = object;
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
VerbData *object = [self.verbs objectAtIndex:indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
#end
DetailViewController.h
#import <UIKit/UIKit.h>
#import "VerbData.h"
#interface DetailViewController : UITableViewController <UISplitViewControllerDelegate>
#property (strong, nonatomic) VerbData *detailItem;
#property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
#property (weak, nonatomic) IBOutlet UILabel *jeOutlet;
#property (weak, nonatomic) IBOutlet UILabel *tuOutlet;
#property (weak, nonatomic) IBOutlet UILabel *ilOutlet;
#property (weak, nonatomic) IBOutlet UILabel *nousOutlet;
#property (weak, nonatomic) IBOutlet UILabel *vousOutlet;
#property (weak, nonatomic) IBOutlet UILabel *ilsOutlet;
#end
DetailViewController.m
#import "DetailViewController.h"
#interface DetailViewController ()
#property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)configureView;
#end
#implementation DetailViewController
#pragma mark - Managing the detail item
#synthesize detailItem = _detailItem;
#synthesize jeOutlet = _jeOutlet;
#synthesize tuOutlet = _tuOutlet;
#synthesize ilOutlet = _ilOutlet;
#synthesize nousOutlet = _nousOutlet;
#synthesize vousOutlet = _vousOutlet;
#synthesize ilsOutlet = _ilsOutlet;
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
if (self.masterPopoverController != nil) {
[self.masterPopoverController dismissPopoverAnimated:YES];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = self.detailItem.english;
self.jeOutlet.text = self.detailItem.je;
self.tuOutlet.text = self.detailItem.tu;
self.ilOutlet.text = self.detailItem.il;
self.nousOutlet.text = self.detailItem.nous;
self.vousOutlet.text = self.detailItem.vous;
self.ilsOutlet.text = self.detailItem.ils;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.title = self.detailItem.infinitive;
[self configureView];
}
- (void)viewDidUnload
{
[self setJeOutlet:nil];
[self setTuOutlet:nil];
[self setIlOutlet:nil];
[self setNousOutlet:nil];
[self setVousOutlet:nil];
[self setIlsOutlet:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#pragma mark - Split view
- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
barButtonItem.title = NSLocalizedString(#"Master", #"Master");
[self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
self.masterPopoverController = popoverController;
}
- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
// Called when the view is shown again in the split view, invalidating the button and popover controller.
[self.navigationItem setLeftBarButtonItem:nil animated:YES];
self.masterPopoverController = nil;
}
#end
First thing I will try to debug is -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method. Is it return values? Try to put NSLog in this method and check it.
Or maybe this will help you:
Note: If you want to change the background color of a cell (by setting the background color of a cell via the backgroundColor property declared by UIView) you must do it in the tableView:willDisplayCell:forRowAtIndexPath: method of the delegate and not in tableView:cellForRowAtIndexPath: of the data source. Changes to the background colors of cells in a group-style table view has an effect in iOS 3.0 that is different than previous versions of the operating system. It now affects the area inside the rounded rectangle instead of the area outside of it.
The code must handle the case where dequeueReusableCellWithIdentifier answers nil...
static NSString *CellIdentifier = #"VerbCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

how to send data backword from second class to first class in iphone

i am try to exchange the one cell to the value of other cell but my value is not transfer proper bec my value is passing second class to first class but not string value is passing array reference why what is the mistake in my code can u help me
for this i create delegate method
this is my originstart.h file
import
#import "RegexKitLiteDemoAppDelegate.h"
#class airport;
#protocol OriginstartDelegate <NSObject>
#required
- (void)Originstart:(NSString *)Origin forIndexPath:(NSIndexPath *)indexPath;
#end
#interface Originstart : UITableViewController {
RegexKitLiteDemoAppDelegate *app;
airport *selectedAirport;
}
#property(nonatomic,retain)NSString*name;
#property(nonatomic,retain)airport *selectedAirport;
#property (nonatomic, copy) NSIndexPath *indexPathToChange;
#property (nonatomic, assign) id<OriginstartDelegate> delegate;
#end
this is my orginestart.m file
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return app.lstAirports.count;
}
// Customize the appearance of table view cells.
- (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];
}
airport* a=(airport*)[app.lstAirports objectAtIndex:indexPath.row];
NSLog(#"str:%#",a);
cell.textLabel.text =a.Name;
cell.detailTextLabel.text=a.Code;
// Configure the cell...
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *newStation = [[app.lstAirports objectAtIndex:indexPath.row]description];
[delegate Originstart:newStation forIndexPath:self.indexPathToChange];
[self.navigationController popViewControllerAnimated:YES];
}
this is my Tfirst.m file
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"accessory selected");
if ([indexPath section] == 0)
{
// load the appropriate view for the accessory selected
if ([indexPath row] == 0)
{
Originstart *viewtwo = [[Originstart alloc] initWithStyle:UITableViewStyleGrouped];
viewtwo.indexPathToChange = indexPath;
viewtwo.delegate = self;
[self.navigationController pushViewController:viewtwo animated:YES];
[viewtwo release];
}
else{
NSLog(#"accessory right");
}
}
}
#pragma mark - Delegate protocol method
- (void)Originstart:(NSString *)Origin forIndexPath:(NSIndexPath *)indexPath {
[datasource replaceObjectAtIndex:indexPath.row withObject:Origin];
[self.tableView reloadData];
}
this is my airport.h file where i create two string variable and one array for take value and display for in originstart classwith name and code i writen this in here in class
originstart.m airport* a=(airport*)[app.lstAirports objectAtIndex:indexPath.row];
NSLog(#"str:%#",a);
cell.textLabel.text =a.Name;
cell.detailTextLabel.text=a.Code;
and final this class arport class
//
// airport.h
// RegexKitLiteDemo
//
// Created by pradeep.yadav on 9/13/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#interface airport : NSObject {
NSString *Code;
NSString *Name;
NSArray *DestinationAirports;
}
#property(nonatomic,retain)NSString *Code;
#property(nonatomic,retain)NSString *Name;
#property(nonatomic,retain)NSArray *DestinationAirports;
#end
To achieve what u want , just try these steps:
1.First, create a property of first class in the second class.
2.In the first class create those variables or objects as properties to which u want to pass the data from the second class.
3.(Hope u are using navigation controller based app ) While pushing from the first to second view controller u create a instance of the second class and pass it pushViewController method. Add the following line of code along with it.....
secondViewObj.firstView=self;
where secondViewObj is the instance of the secondViewController class and firstView is the property declared in that second class.
4.Now in the second class when u want to pass the data to first class just add the following line of code:
firstView.dataMember1=value;
where dataMember1 is the variable or object which was created as a property as mentioned in the 2nd point. Hope this helps.
In the FirstViewController class where u push to SecondviewController have the following piece of code:
SecondViewController *svc = [SecondViewController alloc]init];
svc.vc = self;
[self.navigationController pushViewController:svc animated:YES];
and also have a property declared for the data u want to pass to the firstView Controller.
In this case it s going to be a integer variable.
#property (nonatomic) int selectedValue and also synthesize it.
Now in the secondViewController , declare a property for the firstViewController like this
#property (nonatomic, retain) FirstViewController *vc; and synthesize it.
Where u want to pass the data to the FirstViewController have the following code,
vc.selectedValue = 1;
Now after popping back to the firstViewController , if u chk the value of the selectedValue variable u will find the value has been passed from second to first.
Hope this helps..
The simplest apprroach is to set an object in FirstViewController here is the way
SecondViewController
FirstViewController *instanceOfFirstView;
#property (nonatomic, retain) FirstViewController *instanceOfFirstView;
#synthesize instanceOfFirstView;
[instanceOfFirstView setValueNeedTobeBroughtFromSecondView:#"VAlue set"]
FirstViewController
NSString *valueNeedTobeBroughtFromSecondView;
#property (nonatomic, retain) NSString *valueNeedTobeBroughtFromSecondView;
#synthesize valueNeedTobeBroughtFromSecondView;
SecondViewController *aSecondViewController=[[SecondViewController alloc] init];
[aSecondViewController setInstanceOfFirstView: self];

NSArray causing memory leak when simulated low memory warning

I have made a sample project that reproduces this issue which contains two views:
root header:
#import <UIKit/UIKit.h>
#import "view2.h"
#interface RootViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
view2 *secondView;
UITableView *table;
NSArray *array;
}
#property (nonatomic, retain) view2 *secondView;
#property (nonatomic, retain) IBOutlet UITableView *table;
#property (nonatomic, retain) NSArray *array;
#end
root main:
#import "RootViewController.h"
#implementation RootViewController
#synthesize table, array, secondView;
- (void)viewDidLoad
{
[super viewDidLoad];
if(self.array == nil){
self.array = [NSArray arrayWithObjects:#"1", #"2", #"3", #"4", nil];
}
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
[super viewDidUnload];
table = nil;
array = nil;
secondView = nil;
}
- (void)dealloc
{
[table release];
[array release];
[secondView release];
[super dealloc];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
- (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.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (secondView == nil) {
secondView = [[view2 alloc] init];
}
[self.navigationController pushViewController:secondView animated:YES];
}
#end
view2 simple contains a label with the text "view 2" for identification purposes.
All this code is doing in the root controller is creating an array with the values 1,2,3,4 and binding this text as rows to the table, clicking any row pushes view 2 onto the stack.
if you load up the app in the simulator using the leaks instruments tool, click on any row so that view2 is displayed and then simulate an error warning the following leaks appear:
image
for the line:
self.array = [NSArray arrayWithObjects:#"1", #"2", #"3", #"4", nil];
this is causing me a lot of problems in my main app as i am using arrays to provide data in tables all over the place.
i have tried various ways to fix this such as declaring the array in different ways to no avail.
any help is greatly appreciated!
thanks
In viewDidUnload you're mixing up property vs. direct ivar access.
array = nil simply sets the ivar to nil without using the synthesized accessor method. You have to use the dot notation: self.array = nil;
This way the accessor setArray: is used which handles memory management for you.
Mixing up ivars and properties is a frequent problem amongst Objective-C beginners. The confusion can easily be prevented by always using different names for properties and ivars:
#synthesize array = _array;
You can just leave out the ivar declaration in the class's #interface or name it as in the #synthesize directive.

Accessing instance variables from UITableView delegate methods

Question:
I'm trying to access a variable from the UITableView tableView:didSelectRowAtIndexPath: delegate method. The variable can be accessed from the data source methods, but when I try to access it from delegate methods such as this one, the app crashes.
I declare the variable in my .h file, and initialise it in .m file in the applicationDidFinishLaunching method. I haven't declared any accessors/mutators.
The weird thing is that the problem doesn't occur if I declare the variable like this:
helloWorld = #"Hello World!";
...but it does if I declare the variable like this:
helloWorld = [NSString stringWithFormat: #"Hello World!"];
Any ideas on what may be going on here? What am I missing?
Full code:
UntitledAppDelegate.h:
#import <UIKit/UIKit.h>
#interface UntitledAppDelegate : NSObject <UIApplicationDelegate, UITableViewDelegate, UITableViewDataSource> {
UIWindow *window;
NSString *helloWorld;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#end
UntitledAppDelegate.m:
#import "UntitledAppDelegate.h"
#implementation UntitledAppDelegate
#synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
helloWorld = [NSString stringWithFormat: #"Hello World!"];
NSLog(#"helloWorld: %#", helloWorld); // As expected, logs "Hello World!" to console.
[window makeKeyAndVisible];
}
- (void)dealloc {
[window release];
[super dealloc];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
}
cell.textLabel.text = #"Row";
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"helloWorld: %#", helloWorld); // App crashes
}
#end
You need to retain your helloWorld instance variable. Try this:
helloWorld = [[NSString stringWithFormat: #"Hello World!"] retain];
It worked in the first instance because static strings are 'infinitely retained', and so are never deallocated. In the second, your instance variable is being released once the event loop runs. Retaining it will prevent this.