Why is my Objective-C object being deallocated after viewDidLoad: is called? - ios

The object created deallocated after viewDidLoad: method in Cocoa
Please see the code below:
#import "ShowTableViewController.h"
#interface ShowTableViewController ()
#property NSArray *data;
#end
#implementation ShowTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.data = #[#"One", #"Two", #"Three"];
NSLog(#"%ld",self.data.count);
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
NSLog(#"%ld",self.data.count);
return self.data.count;
}
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
return self.data[row];
}
#end
The output is
3
0
I checked the execution order using breakpoints viewDidLoad is called first!
I resolved it by using awakeFromNib method. but i want to know why this is happening
Any help would be appreciated.

You need to reload your tableView in viewDidLoad after assigning your array like this
- (void)viewDidLoad {
[super viewDidLoad];
self.data = #[#"One", #"Two", #"Three"];
[self.tableView reloadData];
NSLog(#"%ld",self.data.count);
}
This have solved my problem, hope it will solve your too.

I had to objects in total. One in the interface builder and another one created by me in code. the object was not getting deallocated. the second object was assigned as the datasource, so it was returning zero. Its a honest mistake on my part. Sorry for wasting your time. Thanks you all for the answers :)

Try to declare your data property as strong
#property NSArray *data;
becomes
#property (strong) NSArray *data;

Related

Objective-c UITableView separate class cellForRowAtIndexPath does not get called

There are a huge number of questions relating to this topic but I have not yet come across my use case so here goes.
This is my first couple weeks in OBJ-C so I have no clue what I am doing with some of this stuff...
What I Want
I do not particularly enjoy seeing so many classes in OBJ-C that overload the view controller classes with every and any function on this earth. It looks dirty and feels gross as far as OOP goes. In my use case I don't have a full screen table just a little one to hold 10 things. Therefore it's quite inappropriate to use a full UITableViewController. Instead, I want to have all my table delegate specific methods to be in a UITableView sub-class. NOT in a UITableViewController or a ViewController with a UITableView property. This should be mega simple yet...
The Problem
No matter what I do I cannot seem to get the method cellForRowAtIndexPath to fire. I know enough to know that this stuff relies heavily on the delegate and datasource assignment... however since I have a separate UITableView class that uses the <UITableViewDelegate, UITableViewDataSource> delegations I don't think I should have to do any sort of assignment at all!
What am I gonna write?? self.delegate = self ? or worse, in the ViewController that calls this UITableView class, self.tasksTable.delgate = self.tasksTable ? Eww... gross
Here is what I am doing in code.
The Code
TasksTableView.h
#import <UIKit/UIKit.h>
#interface TasksTableView : UITableView <UITableViewDelegate, UITableViewDataSource> {
NSArray *tasksData;
}
- (NSMutableArray *)getAllTasks;
#end
TasksTableView.m
#import "TasksTableView.h"
#import "NSObject+RemoteFetch.h" //<--I use this to fetch, obvs
#interface TasksTableView ()
#property (nonatomic, strong) NSString *cellId;
#end
#implementation TasksTableView
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if(self) {
_cellId = #"AllTasksTableCell";
tasksData = [self getAllTasks];
}
return self;
}
#pragma mark - Custom Table Functionality
- (NSMutableArray *)getAllTasks {
#try {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *TASKS_URL = [userDefaults objectForKey:#"tasksUrl"];
NSObject *fetcher = [[NSObject alloc] init];
NSDictionary *response = [fetcher fetchAPICall:TASKS_URL httpRequestType:#"GET" requestBodyData:nil];
return [response objectForKey:#"data"];
} #catch (NSException *exception) {
NSLog(#"could not get tasks, error: %#", exception);
return nil;
}
}
#pragma mark - UITableView DataSource Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tasksData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//<-- NEVER GETS HERE
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:_cellId];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:_cellId];
}
cell.textLabel.text = [tasksData objectAtIndex:indexPath.row];
return cell;
}
#end
I am also having a hard time figuring out what to set as the datasource. In other languages you would typically set the DataSource object with self.DataSource = [self getAllTasks]... however all the tuturials I have done thus far all tend to use some weird ad-hoc NSArray or NSDictionary to then correlate the index of the table functions with the index of the array or dictionary keys... This confuses me greatly as to why I can't just set the DataSource object and have the table know to iterate over it's data.
My conclusion is that this isn't firing because it thinks the DataSource object is empty and there are no rows? (which it is, but like I said people seem to get Tables to work fine on YouTube doing this)
Thanks.
TasksTableView class is derived from UITableView class & You are implementing the UITableview delegates in the same class. This will not work.
Instead of creating a UITableView subclass. Create TasksTableView class as NSObject sub class. And pass the tableview object from where you added a tableview.
#interface TasksTableView : NSObject <UITableViewDelegate, UITableViewDataSource> {
NSArray *tasksData;
__weak UITableView *tableView;
}
And set that table view delegate to self(TasksTableView object) while init the TasksTableView Class
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if(self) {
_cellId = #"AllTasksTableCell";
tasksData = [self getAllTasks];
self.tableView.delgate = self;
self.tableView.datasource = self;
}
return self;
}
Now your delegate methods will trigger for that specific tableview

NSUndoManager removeAllActionsWithTarget crash

I have some abbreviated iOS Objective-C sample code (simplified from a larger project) that causes a crash in NSUndoManager that I can't explain.
Namely, when an object that is only held onto by the NSUndoManager deallocs (because it's beyond the levels of undo), and, according to the docs calls removeAllActionsWithTarget:self, I get an EXC_BAD_ACCESS.
// SimpleViewController.m
#interface ViewController ()
#property (nonatomic, strong) NSUndoManager *undoManager;
#end
#implementation ViewController
#synthesize undoManager;
// called from a simple button
- (IBAction)doItTapped:(id)sender
{
CoolObject *object = [CoolObject new];
object.undoManager = self.undoManager;
// according to docs, object will be retained by NSUndoManager here
// but target will not (which should be okay)
[self.undoManager registerUndoWithTarget:self selector:#selector(notCool:) object:object];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.undoManager = [NSUndoManager new];
self.undoManager.levelsOfUndo = 3;
}
and
// CoolObject.m
#implementation CoolObject
- (void)dealloc
{
[self.undoManager removeAllActionsWithTarget:self];
}
#end
After the 4th tap of the button (levelsOfUndo + 1), it crashes.
If I swap NSUndoManager with GCUndoManager, no crash.
Tested in iOS 10.2 sim and devices.
Thanks for any ideas!
Their are chances that you might be getting this error because self.undoManager is not retained at that point where you are using it. When the object is already deallocated and you try to access it, you will get bad access exception.
Try to change your code from this:
CoolObject *object = [CoolObject new];
to this:
#interface ViewController (){
CoolObject *object;
}
#property (nonatomic, strong) NSUndoManager *undoManager;
#end
#implementation ViewController
- (IBAction)doItTapped:(id)sender
{
object = [CoolObject new];
object.undoManager = self.undoManager;
// according to docs, object will be retained by NSUndoManager here
// but target will not (which should be okay)
[self.undoManager registerUndoWithTarget:self selector:#selector(notCool:) object:object];
}
#end
Hope this will help.
Just like me, you seem to have misinterpreted the admittedly inaccurately written documentation. The docs talk about "target", "object" and "target object" as if they were different things when they really mean exactly one and the same: the (id)target parameter of -removeAllActionsWithTarget:
In other words, in my opinion you should not need to call -removeAllActionsWithTarget: inside of CoolObject at all because CoolObject has been specified as the object of -registerUndoWithTarget:selector:object: whereas the target is your ViewController.
You may have to call -removeAllActionsWithTarget: in your NSViewController's -dealloc but even that is unnecessary in your example because your NSViewController owns the NSUndoManager and thus ViewController won't go away before undoManager does.

Update property used in a tableView from another viewController

I have FirstViewController and SecondTableViewController. In SecondTableViewController.m, I create a cell in the cellForRow... method where the cell.textLabel.text is a string from an NSInteger property ("count") of the SecondTableViewController.
I would like a button in FirstViewController to increment the value of count.
I've tried making a property of FirstViewController and then using that:
#property SecondTableViewController *viewController;
and
- (IBAction)buttonTouched:(id)sender {
self.viewController.count++;
[self.viewController.tableView reloadData];
}
But this way isn't working. count is still its original value of zero. I've also reloaded the table in viewWillAppear and still nothing. How can I do this?
Count being used as a property may be where you are going wrong because count is a method that returns the number of objects in an array that is found in foundation framework. Also keep in mind that if you are storing a integer into a string object try storing it in this format.
cell.textlabel.text = [NSString stringWithFormat: #"%i", count];
Hope this helps
Try following
firstViewController.h
#interface DMFirstViewController : UIViewController
#property (nonatomic, strong) DMSecondViewController * secondController;
- (IBAction)buttonPressed:(id)sender;
#end
firstViewController.m
- (IBAction)buttonPressed:(id)sender
{
++self.secondController.count;
[self.navigationController pushViewController:self.secondController animated:YES];
}
secondViewController.h
#property (nonatomic) int count;
secondViewController.m
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(#"%d", self.count);
}
EDIT
Check out those two images and implement the similar logic and get the solution.
----- END OF NEW EDIT -----
OLD
I think you haven't assigned and allocated memory for SecondTableViewController reference i.e, self.viewController of FirstViewController in its viewDidLoad method i.e,
-(void) viewDidLoad //In FirstViewController
{
self.viewController = [[SecondTableViewController alloc] init];
}
and pushed the same reference on to the stack of navigationController after performing button taps to increase the count of count variable of SecondTableViewController.
If you are not clear, comment.

How to access array variable value in the child view

I am trying to access an array defined as property on the parent view from child view and I get an empty array. here is what I did. could someone shed some light please!
FirstTableViewController.h
#interface FirstTableViewController : UITableViewController
#property (nonatomic,retain) NSMutableArray *SomeItems;
#end
in my FirstTableViewController.m. I have code that initialized the SomeItems with values. This has been verified
On the FirstTableViewController view there is a button that displays a second SecondTableView
in SecondTableViewController.m I have
#import "FirstTableViewController.h"
#import "SecondTableViewController.h"
- (void)viewDidLoad
{
[super viewDidLoad];
FirstTableViewController * objParent;
NSLog(#"count = %i",[objParent.SomeItems count]); //this return 0
}
thanks in advance!
EDITED
ToDoListTableViewController.h
#interface ToDoListTableViewController : UITableViewController
#property (nonatomic, strong) NSMutableArray *toDoItems;
- (IBAction)unwindToList:(UIStoryboardSegue *)segue : (id) sender;
#end
ToDoListTableViewController.m
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
//Attempt to pass toDoItems to new view controller.
//CompleteTableViewController.toDoItems = [self.toDoItems copy]; //this line caused compiler error saying toDoItems not found on object of CompleteTableViewController
CompleteTableViewController * objChild = (CompleteTableViewController*)[segue destinationViewController];
if(objChild != nil)
objChild.toDoItems = [self.toDoItems copy];
//sorry for weird code, as I don't really understand how this method really works.
//but I have a feeling I am just some inches away from getting it to work the way i want
}
CompleteTableViewController.h
#interface CompleteTableViewController : UITableViewController
#property (nonatomic,copy) NSMutableArray *toDoItems;
#end
CompleteTableViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"#%i record(s) in Complete Table View", [toDoItems count]);
}
Thanks again!
It is clear that you miss the basilar concept of the OOP.
You declared this:
FirstTableViewController * objParent;
but first of all it is not initializated and second it doesn't point to your instanced viewController.
Other things but that at this point become secondary are:
if you are using ARC, declare the property strong instead of retain;
method and variable should respect the Camel methodology so is not SomeItems but is someItems;
So if you are opening a viewController from another and you want access to that array, the best thing that you could do is pass that array and so have a property like this also in the second viewController:
#property (nonatomic,copy) NSArray *someItems;
and when you press the button in the first viewController, before push the second viewController:
secondViewController.someItems = [self.someItems copy];
Note that in the second view controller the array is not mutable, because probably you want just access to the informations. But this depend from you.
Is a little bit hard explain you more because i see that you are really a newbie. But, i hope to help you.
You need to pass a reference for the parent object through to the child on creation, or simply pass a reference to the array itself.
From Matteo suggestion, this seems to solve my issue
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UINavigationController *navigationController = segue.destinationViewController;
CompleteTableViewController *objChild = (CompleteTableViewController *)navigationController.topViewController;
if(objChild != nil){
objChild.toDoItems = [self.toDoItems copy];
}
}
thanks Matteo.
In the SecondTableViewController, you've declared the FirstTableViewController in viewDidLoad, but that does not mean it's pointing to your previously created FirstTableViewController (you've made no assignment). Before viewDidLoad is called, you need to pass the FirstTableViewController to the SecondTableViewController, assign it to a variable that's not local in scope, and then you can access the FirstTableViewController and/or its SomeItems inside viewDidLoad.
Without knowing more of your design or what you're trying to accomplish, it'd be best to pass SomeItems to SecondTableViewController as part of initializing it if that's all you need from FirstTableViewController. If the state of what you're accessing is going to change as you are going from controller to controller, I'd highly recommend you spend more time reading up on Model-View-Controller (MVC), delegation and possibly Key-Value Observation (KVO). You're missing some fundamental knowledge.
Edit: also agree on naming, SomeItems should be someItems.

Get Access to Object in Obj-c [duplicate]

I am using the iPhone SDK and have an issue doing something simple. I am trying to add an NSNumber object to an NSMutableArray instance variable. I tried adding NSNumber card to NSMutableArray viewedCardsArray, however without breaking, it does not get added to the array. Here is the code.
/////////////////////////////////////////////////////
// Inside the header file Class.h
#interface MyViewController : UIViewController {
NSMutableArray *viewedCardsArray;
//snip ...
}
#property (nonatomic, retain) NSMutableArray *viewedCardsArray;
#end
/////////////////////////////////////////////////////
// Inside the methods file Class.m
#import "StudyViewController.h"
#implementation StudyViewController
#synthesize viewedCardsArray
//snip ...
- (IBAction)doShowCard {
//snip ...
NSNumber *cardIdObject = [[NSNumber alloc] initWithInt:(int)[self.currentCard cardId]];
[viewedCardsArray addObject: cardIdObject];
[cardIdObject release];
}
So this code executes, and does not seem to leak (according to the Leaks performance tool). However when stepping through the code, at no point does CardIdObject appear in viewedCardsArray.
Looking through SO, I know these basic questions are pretty common to ObjC newbies (like me) so apologies in advance!
Have you initialized your viewedCardsArray? If not you need to somewhere - this is usually done in the init method for your class:
- (id)init
{
self = [super init];
if(self) {
viewedCardsArray = [[NSMutableArray alloc] init];
}
return self;
}
Then it is released in the dealloc method:
- (void)dealloc
{
[viewedCardsArray release];
[super dealloc];
}
Perspx has outlined one way of initializing the array. However, you can also use the class methods provided by NSArray:
self. viewedCardsArray = [NSMutableArray array];
This can go in init or elsewhere.
Note: The object will be autoreleased.

Resources