How to reset all tableView data and arrays when click of UIButton? - iphone

I have 1 tabbarcontroller have Login and Complete Tab. I want to click on Logout button in LoginTab, all data and tableview in COmplete tab is reset. I used this code but it not work:
In CompleteTab.m:
-(void) viewDidLoad
{
temp = [[NSMutableArray alloc] init];
iduploadArray= [[NSMutableArray alloc] init];
FileCompletedArray = [[NSMutableArray alloc] init];
DiffArr= [[NSMutableArray alloc] init];
_tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
tableData = [[NSArray alloc] initWithObjects:FileCompletedArray,nil];
// [_tableView setAllowsSelection:YES];
//tableView.dataSource = self;
// [self.view addSubview:tableView];
// [self parseXMLFile:#"x"];
NSURL *url1 = [NSURL URLWithString:#"server.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: url1] ;
....
temp = [FileCompletedArray mutableCopy];
_tableView.dataSource = self;
_tableView.delegate=self;
[self.view addSubview:_tableView];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);//: %#", operation.responseString);
}
];
[httpClient enqueueHTTPRequestOperation:operation];
}
-(void) resetAll
{
[temp removeAllObjects];
[FileCompletedArray removeAllObjects];
[DiffArr removeAllObjects];
[_tableView reloadData];
}
In LoginTab.m:
- (IBAction)LogoutButton:(id)sender {
login = false;
username.hidden = NO;
pass.hidden = NO;
LoginButton.hidden = NO;
LogoutButton.hidden = YES;
//make all the arrays get reset
username.text =#"";
pass.text = #"";
[completeview resetAll];
}
I debug: when I click on Logout button,it called resetAll() function but each variable is 0x000000. So it cannot reset data and reload tableview. Can you help me? Thanks

Since the logout button is in loginTab, it doesnot have any reference to your completeTab. So you need to keep the completeTab reference some where in your app. Best choice is in appDelegate. Then on logout button click, take this instance and reset all data.
Keep your completab view controller instance in AppDelegate like this
#property (nonatomic, retain) UIViewController *completeTab;
self.completeTab = \\Your complete tab viewcontroller instance.
Then on logout button click
[(AppDelegate *)[[UIApplication sharedApplication] delegate].completTab resetAll]
Hope this helps.

Use the selector to call the reset method like this
[completeview performSelector:#selector(resetAll)];

Please create sample project with Tabbased Application.
====== AppDelegate.m ======
#import "LoginTab.h"
#import "CompleteTab.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
UIViewController *viewController1 = [[[LoginTab alloc] initWithNibName:#"LoginTab" bundle:nil] autorelease];
UIViewController *viewController2 = [[[CompleteTab alloc] initWithNibName:#"CompleteTab" bundle:nil] autorelease];
self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.viewControllers = #[viewController1, viewController2];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
#end
====== LoginTab.m ======
#implementation LoginTab
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"LoginTab", #"LoginTab");
self.tabBarItem.image = [UIImage imageNamed:#"LoginTab"];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)LogoutButton:(id)sender {
// Post Notification to CompleteTab Class
[[NSNotificationCenter defaultCenter]
postNotificationName:#"resetAll"
object:self];
}
====== CompleteTab.m ======
#implementation CompleteTab
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"CompleteTab", #"CompleteTab");
self.tabBarItem.image = [UIImage imageNamed:#"CompleteTab"];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(resetAll:)
name:#"resetAll"
object:nil];
return self;
}
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void) resetAll:(NSNotification *) notification
{
NSLog(#"Reset All Called");
}
I am able to call resetAll method of CompeteTab using NSNotification Concept. Please follow this code.

I'd also recommend you check out the free Sensible TableView framework as it has such restting functionality out of box.

As for the method [tableView reloadData] : The table view's delegate or data source calls this method when it wants the table view to completely reload its data. It should not be called in the methods that insert or delete rows, especially within a block implemented with calls to beginUpdates and endUpdates.
I believe you are calling the reloadData in resetAll which is updating the FileCompletedArray which provides the dataSource for the table. Can you call it from somewhere else.

Related

Core data random crash

I finished the development of my app but at this point I face random crashes when I try to save an image in core data.
Here is the console message:
CoreData: error: Serious application error. Exception was caught
during Core Data change processing. This is usually a bug within an
observer of NSManagedObjectContextObjectsDidChangeNotification.
-[_PFExternalReferenceData compare:]: unrecognized selector sent to instance 0x94b69b0 with userInfo (null)
The problem is that it is non deterministic. It happens more or less once out of 5 times.
Would anyone have an idea where I should look for ?
EDIT:
Here is the code of my class that seems to pose a problem. It happens sometimes when I click on the save button, calling -(IBAction)saveResultingImage:
#import "ResultViewController.h"
#interface ResultViewController ()
#property (nonatomic)BOOL resultSaved;
#end
#implementation ResultViewController
#pragma mark - IBActions
- (IBAction)saveResultingImage
{
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
_resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
_resultSaved = [self saveOnCoreData];
[self performSegueWithIdentifier:#"BackToStartSegue" sender:self];
}
- (IBAction)discardWithoutSaving
{
[self performSegueWithIdentifier:#"BackToStartSegue" sender:self];
}
- (IBAction)restartDrawing:(id)sender
{
UIImage *backgroundImage = _subImage;
UIImageView *imageView =
[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
imageView.image = backgroundImage;
[self.view addSubview:imageView];
UIImage *maskImage = _maskImage;
CGRect maskViewRect = CGRectMake(0, 0, maskImage.size.width, maskImage.size.height);
ImageMaskView *subView = [[ImageMaskView alloc] initWithFrame:maskViewRect image:maskImage];
[self.view addSubview:subView];
}
- (IBAction)showExplainVC
{
[self performSegueWithIdentifier:#"ShowInfoSegue" sender:self];
}
#pragma mark - Methods
- (BOOL)saveOnCoreData
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newMeme =
[NSEntityDescription insertNewObjectForEntityForName:#"Meme" inManagedObjectContext:context];
NSData *toSaveMeme = UIImagePNGRepresentation(_resultImage);
[newMeme setValue:toSaveMeme forKey:#"image"];
NSError *error = nil;
if (![context save:&error]) {
DebugLog(#"Can't save: %# %#", error, [error localizedDescription]);
return NO;
}
return YES;
}
#pragma mark - View Controller LifeCycle
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
if ([identifier isEqualToString:#"BackToStartSegue"]) {
return _resultSaved;
}
return _resultSaved;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:NO];
DebugLog(#"Called viewWillAppear");
self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *discardBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"Discard" style:UIBarButtonItemStylePlain target:self action:#selector(discardWithoutSaving)];
UIBarButtonItem *saveBarButtonItem =
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:#selector(saveResultingImage)];
UIBarButtonItem *infoBarButton =
[[UIBarButtonItem alloc] initWithTitle:#"How to" style:UIBarButtonItemStylePlain target:self action:#selector(showExplainVC)];
discardBarButtonItem.style = UIBarButtonItemStyleBordered;
self.navigationItem.rightBarButtonItems = #[saveBarButtonItem, discardBarButtonItem, infoBarButton];
self.view.backgroundColor = [UIColor blackColor];
[self restartDrawing:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Core Data Stack
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
#end
Thanks for showing interest :-)

Switching ViewControllers, but nothing happens?

I want to put the code of switching ViewControllers to a single class, which named SwitchController. But nothing happens.
Here is the code:
//AppDelegate.m
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
RootViewController *root = [[RootViewController alloc] init];
[self.window setRootViewController:root];
[self.window makeKeyAndVisible];
return YES;
}
//SwitchController.h
#interface SwitchController : NSObject
#property (strong,nonatomic) RootViewController *rootViewController;
+(SwitchController *)sharedInstance;
-(void)requestToSwitchViewController:(NSInteger)tag;
#end
//SwitchController.m
#import "SwitchController.h"
#import "FirstViewController.h"
#import "SecondViewController.h"
#implementation SwitchController
#synthesize rootViewController = _rootViewController;
-(id)init
{
self = [super init];
if (self == nil)
{
_rootViewController = [[RootViewController alloc] init];
}
return self;
}
+(SwitchController *)sharedInstance
{
static SwitchController *sharedSingleton = nil;
#synchronized([SwitchController class])
{
if(sharedSingleton == nil)
{
sharedSingleton = [[self alloc] init];
}
}
return sharedSingleton;
}
-(void)requestToSwitchViewController:(NSInteger)tag
{
switch (tag)
{
case 1:
{
FirstViewController *first = [[FirstViewController alloc] init];
[self.rootViewController presentViewController:first animated:YES completion:nil];
}
break;
......... //Do something else
default:
break;
}
}
#end
//This is the self.window.rootViewController------RootViewController.m
//In this ViewController's view, there is a button, and on press, it will do the following thing
- (IBAction)pressed:(id)sender
{
[[SwitchController sharedInstance] requestToSwitchViewController:[(UIButton *)sender tag]];
}
So, is there anything wrong with my code?
Why does nothing happens when I press the button?
There may be several issues..
1) Check whether your button outlet is correctly connected to this method -(IBAction)pressed:(id)sender;
2)Add this line after #synthesize in SwitchController.m
static SwitchController *sharedSingleton = nil;
3)change your method like this
+(SwitchController *)sharedInstance
{
if(sharedSingleton == nil)
{
sharedSingleton = [[self allocWithZone:NULL] init];
}
return sharedSingleton;
}
4) Remove this line from the -id(init) method
// You do not need to re-initialize the root view controller
_rootViewController = [[RootViewController alloc] init];
5) Check whether the button is valid. Before calling this method requestToSwitchViewController: check what it logs
UPDATE:
Try like this: (For this, you need to create a property for navigation controller in your appDelegate and synthesize it)
switch (tag)
{
case 1:
{
FirstViewController *first = [[FirstViewController alloc] init];
appDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.navigationController presentViewController:first animated:YES completion:nil];
}
.....
.........
}
I guess you're just defining the viewController, you need to define the View too. they're different things.

Viewdid load method call on popview

In my application i set some animations in View1's view load() ,At first launch its working propely,if im pushed into otherview ,and while pop into view1 its not animating,What shoud i do for animate while pop view from other view?here my view did load code,
- (void)viewDidLoad
{
artext=[[NSMutableArray alloc] init];
arimage=[[NSMutableArray alloc] init];
arsound=[[NSMutableArray alloc] init];
[super viewDidLoad];
[self copysqlitetodocuments];
[self Readthesqlitefile];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"classroom.png"]];
}
i tried with
- (void)viewDidAppear:(BOOL)animated
{
[self buttonmover];
[super viewDidAppear:animated];
}
its not working,Can any one pls help me to solve this problem
If you want to execute code when the view appears (e.g. an animation), -viewDidLoad is the wrong place to do it.
You should probably use:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// ...
}
Try in viewWillAppear
-(void)viewWillAppear:(BOOL)animated
{
artext=[[NSMutableArray alloc] init];
arimage=[[NSMutableArray alloc] init];
arsound=[[NSMutableArray alloc] init];
[self copysqlitetodocuments];
[self Readthesqlitefile];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"classroom.png"]];
}
When your viewDidLoad method is called, the controller isn't yet in the view hierarchy, so the animations doesn't work.
You have to perform animations in viewWillApper, after implementing the method [super viewWillAppear]. Something like:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
artext = [[NSMutableArray alloc] init];
arimage = [[NSMutableArray alloc] init];
arsound = [[NSMutableArray alloc] init];
[self copysqlitetodocuments];
[self Readthesqlitefile];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"classroom.png"]];
}

returning null inside tableview delegate

HI
I am working on UITablview based project. i like to load a new view when ever a cell got click. i am using following code in didselectRowAtIndexPath delegate method.
The below coding is not showing any error but new view not get load and [self navigationController] is returning null.
inside Viewdidload function [self navigationcontroller] returning proper value. but inside Delegate method [self navigationcontroller] returns null.
/// inside appDelegate class
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.viewController = [[LAMainViewController_iPhone alloc]initWithNibName:#"LAMainViewController_iPhone" bundle:nil];
UINavigationController *controller = [[UINavigationController alloc]initWithRootViewController:viewController];
[window addSubview:controller.view];
[controller release];
[window makeKeyAndVisible];
return YES;
}
/// inside LAmainviewcontroller.m
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
//self.navigationController.navigationBar.backgroundColor =[UIColor clearColor];// .title=#"test";
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *materialPlistPath = [[NSBundle mainBundle]pathForResource:#"materials" ofType:#"plist"];
materialList = [[NSArray alloc]initWithContentsOfFile:materialPlistPath];
materialTable.backgroundColor = [UIColor blackColor];
NSLog(#" dud kiad navigationController %#", self.navigationController);
//2010-10-20 15:22:03.809 LabAssistant[17368:207] dud kiad navigationController <UINavigationController: 0x5f3b160>
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
self.navigationController.navigationBarHidden = YES;
NSIndexPath *indexPath = [materialTable indexPathForSelectedRow];
[materialTable deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
LAMaterialPropertiesViewController_iPhone *materialPropertyListView = [[[LAMaterialPropertiesViewController_iPhone alloc] initWithNibName:#"LAMaterialPropertiesViewController_iPhone" bundle:nil] autorelease];
materialPropertyListView.chemicalName = [[materialList objectAtIndex:[indexPath row]] objectForKey:#"materialProperty"];
[[self navigationController] pushViewController:materialPropertyListView animated:YES];
NSLog(#"%#",[self navigationController]);
///2010-10-20 16:20:42.634 LabAssistant[17656:207] navigationController (null)
}
please help me to fix this issue.
thanks!
Remove the autorelease from the init statement. Actually the viewcontroller is getting released before it gets pushed.
instead of
LAMaterialPropertiesViewController_iPhone *materialPropertyListView = [[[LAMaterialPropertiesViewController_iPhone alloc] initWithNibName:#"LAMaterialPropertiesViewController_iPhone" bundle:nil] autorelease];
try this
LAMaterialPropertiesViewController_iPhone *materialPropertyListView = [[LAMaterialPropertiesViewController_iPhone alloc] initWithNibName:#"LAMaterialPropertiesViewController_iPhone" bundle:nil];
Hope this will solve your problem.
I think the table view delegate is called before the navigation controller is set to the view controller.
Can you try reloading the tableview [tableview reloadData]; in viewWillAppear or viewDidAppear?

Why does my TTTableViewController not appear

I have an application which contains a scrollview with two subviews (to scroll left and right between them)
Both views appear correctly and scrolling between the views worked fine. Now I want to change the first view to be a TTTableView (courtesy of Three20) but when I use the class 'TableControlsTestController' from the TTCatalog application all I see is an empty tableView
Note that this class contains all the data to display 6 cells
To add the new TTTableView I use the following
[scrollView addSubview:detailView.view];
where detailView is the instance of TableControlsTestController
To try and narrow down where the problem is I also tried calling
[self presentModalViewController:detailView animated:YES];
This correctly displays the tableview with the 6 cells.
Why when I try to add the view to the scrollView does this not work as I expect?
For reference if you do not have access to the TTCatalog
#import "TableControlsTestController.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
#implementation TableControlsTestController
///////////////////////////////////////////////////////////////////////////////////////////////////
// NSObject
- (id)init {
if (self = [super init]) {
self.tableViewStyle = UITableViewStyleGrouped;
self.autoresizesForKeyboard = YES;
self.variableHeightRows = YES;
UITextField* textField = [[[UITextField alloc] init] autorelease];
textField.placeholder = #"UITextField";
textField.font = TTSTYLEVAR(font);
UITextField* textField2 = [[[UITextField alloc] init] autorelease];
textField2.font = TTSTYLEVAR(font);
textField2.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
TTTableControlItem* textFieldItem = [TTTableControlItem itemWithCaption:#"TTTableControlItem"
control:textField2];
UITextView* textView = [[[UITextView alloc] init] autorelease];
textView.text = #"UITextView";
textView.font = TTSTYLEVAR(font);
TTTextEditor* editor = [[[TTTextEditor alloc] init] autorelease];
editor.font = TTSTYLEVAR(font);
editor.backgroundColor = TTSTYLEVAR(backgroundColor);
editor.autoresizesToText = NO;
editor.minNumberOfLines = 3;
editor.placeholder = #"TTTextEditor";
UISwitch* switchy = [[[UISwitch alloc] init] autorelease];
TTTableControlItem* switchItem = [TTTableControlItem itemWithCaption:#"UISwitch" control:switchy];
UISlider* slider = [[[UISlider alloc] init] autorelease];
TTTableControlItem* sliderItem = [TTTableControlItem itemWithCaption:#"UISlider" control:slider];
self.dataSource = [TTListDataSource dataSourceWithObjects:
textField,
editor,
textView,
textFieldItem,
switchItem,
sliderItem,
nil];
}
return self;
}
#end
It turns out that some of the events were not being propagated through the scrollView and therefore not handled in the TTTableViewController. To fix this I had to do the following in my scrollView
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[myNewTTViewController viewWillAppear:NO];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[myNewTTViewController viewDidAppear:NO];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[myNewTTViewController viewWillDisappear:NO];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[myNewTTViewController viewDidDisappear:NO];
}
As soon as I did this the table popped into life