UITableViewCells loaded from NIB always nil - iphone

I'm trying to create a simple form using a UITableViewController as documented in the Apple Developer Documentation here.
What I'm trying to do is located in the section entitled: "The Technique for Static Row Content"
I've created a couple of UITableViewCells and added them to my nib, but when I try and access them to add them to the UITableView (in the cellForRowAtIndexPath: method) they are always null.
It's like they are not being properly loaded from the nib. I've double/triple/quadruple checked my code to make sure I'm doing it exactly as detailed in the docs, but no luck.
Is there something obvious I'm missing here?

Have you made sure you've connected the IBOutlets in the nib file?
In your ViewController.h file you should have:
IBOutlet UITableViewCell *specialCell1;
IBOutlet UITableViewCell *specialCell2;
and then each of these should be "wired up" to the corresponding cell in the nib file. If not, they won't exist!

Figured it out...
When I added my parent view controller, I was using the simple "init". Switching to "initWithNibName" resolved the issue...
Still learning... :)

Related

UITableView registerNib:forCellReuseIdentifier:

I saw this used in a WWDC video but only very briefly. They didn't go in to how to create the actual xib file.
I've got a UITableViewCell subclass called MyCustomCell. In this I have several properties UILabels, UIImageViews, etc... all set up as IBOutlets.
Now, in my xib file...
What do I set as the file's owner? Where do I reference my MyCustomCell class is this the file's owner?
Once I've set the file's owner how do I link it with the root view of the xib?
I've tried a few settings but I keep getting errors when using it.
Oh, the code I'm using to register it is...
self.cellNib = [UINib nibWithNibName:#"MyCustomCell" bundle:nil];
[self.tableView registerNib:self.cellNib forCellReuseIdentifier:#"CustomCell"];
Thanks
Normally you don't have to bother about the File's owner in that case, because when the tableView instantiates the cell from the provided/associated UINib along with the reuseIdentifier. It will load all the top-level objects of the nib, and use only the first top-level object that is of class UITableViewCell (or maybe just the first top-level-object regardless of the class? but in general you only have your UITableViewCell in your XIB anyway — without counting the File's Owner and the First Responder which are only "proxies").
In fact, the tableView will try to dequeue a cell and if it doesn't find a reusable one, it will create a new one using the UINib you provided. It will be something similar to this:
NSArray* topLevelObjects = [self.cellNib instantiateWithOwner:nil options:0];
cell = [topLevelObjects objectAtIndex:0];
(That's of course a simplified version just to show the idea, I don't know if it actually calls these exact lines, but it should be quite close)
So the File's Owner is not used in this particular case, and you only need to put a simple custom UITableViewCell as the only top-level-object of your XIB file next to the existing File's Owner anf First Responder (that, again, are only "proxies" / "External Objects references" and won't be instantiated and won't be part of the top-level-objects returned by instantiateWithOwner:options:).
If it still doesn't work:
Ensure that you correctly filled the reuseIdentifier of your UITableViewCell in IB (in the Object Inspector pane on the right once you selected your cell in IB), and used the exact same value for this reuseIdentifier property in IB that the one you use in your code.
If still no luck, please provide more info, especially what kind of error, log message or exception you have.
I've found the code given in the question is fine, but you can't refer to self.tableView in the init method if you're using storyboards. There's some discussion about it in another question.
So the first line goes in the init:
self.cellNib = [UINib nibWithNibName:#"MyCustomCell" bundle:nil];
But this line should go in viewDidLoad or similar:
[self.tableView registerNib:self.cellNib forCellReuseIdentifier:#"CustomCell"];
That fixes my mysterious error, e.g. "*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle <Foo.app> (loaded)' with name 'Ogf-Sj-1ej-view-bBf-Ti-Dda''"
And, yes, I'm doing something very similar to scoop things out of Storyboards and place them in xibs for reuse across view controllers!
In addition to Answer from "AliSoftware" Note the least obvious thing out here is that the UITableViewCell has to be the Root View *ABOVE* even the UIView. By default when I selected a new IB file it creates a UIView. So deleting the UIView helps. Thanks.
PS: I wanted to comment on that answer but for some strange reason I can't comment, can only answer. Guess I need a certain rating.

Connecting an IBOutlet to a view within a scrollview within a tab view crashes app. Any ideas?

I used the tabview setup to create an app that has several tabs. One tab has a UIScrollView on it which loads 12 different views into 12 pages. I tried adding a button and imageview to one of the views and now it crashes. I've pored over every single question on here I can find, and have tried every suggested solution, but to no avail. The error that I get is the famous "this class is not key value coding-compliant for the key foo" error. As with everyone else who had this problem, if I disconnect the outlet, it works fine. I've checked and rechecked the class for the nib and it points to the right place.
So I'm not even sure where to go next.
I could post some code, but I don't even know what code would be helpful to post. I'm hoping someone just says, "Um yeah, you can't have a scroll view with multiple views in it and expect to have functionality on each page." That would be helpful!
Page2.h:
#import <UIKit/UIKit.h>
#interface Page2 : UIViewController {
IBOutlet UIImageView *infoImage;
}
#property (retain, nonatomic) UIImageView *infoImage;
(IBAction) showInfo:(id)sender;
#end
Page2.m:
- (IBAction)showInfo:(id)sender {
// do something please!
}
Then in the nib file I CTRL-dragged from "touch-up inside" on my button to the Files Owner and chose "showInfo" ... and I CTRL-dragged from Files Owner down to my UIImageView and chose infoImage.
CRASH
I am not cool enough to insert an image: http://i.stack.imgur.com/KjWhk.png
You still have an outlet connected in your nib that you no longer have defined in your class. You'll see in the inspector that it has turned gray. Disconnect it, and the error should be gone.
are u able to create any other outlet in the same Nib file, as i used to get the same crash, and it got fixed only when i duplicated the same nib, i had implemented almost all methods to solve it. If i am not wrong , this link can help you out https://discussions.apple.com/thread/2431110?start=0&tstart=0
I have sent you the email and attached your project. Hope its working at your end now.
Happy Coding!

Extending a UIViewController with a different NIB file

Ok, I am definitely doing something wrong here...
I have create a BaseViewController that is the datasource and delegate of an matching NIB file containing a UITableView. This controller is responsible pretty much for getting data from a remote web service, creating the cells, and populating the UITableView.
So now I want to create a SearchViewController, so that I can get a UISearchBar that a user can enter a search query, post it on the web service, get the results and populate a UITableView.
However most of the code (in retrieving the data/populating the UITableView) exists in BaseViewController. So the first thing I thought of is to create the SearchViewController as an extension of BaseViewController with a different NIB file.
I've created the new NIB file called SearchView containing a UISearchBar and a UITableView and linked those two with the File Owners IBOutlets. (The UITableView IBOutlet is being inherited from BaseViewController)
So finally in my MainWindow.xib I've added a TabBarController and from the IB I've linked the UINavigationController to load the SearchViewController with View being loaded from SearchView. When I switch to the search tab, I am getting a SIG_ABORT with error:
-[UITableViewController loadView] loaded the "SearchView" nib but didn't get a UITableView
Could anyone point me in the right direction on how to proceed? I am sure most of you doing stuff with UITableView have reused code by extended a class. Is this the correct approach?
I'm not sure that I follow your description exactly, but what I think you should do is create your SearchViewController as a subclass of BaseViewController, like
#interface EventListViewController : UIViewController { ... }
Is that what you mean by "extending" BaseViewController?
And then you're using [[SearchViewController alloc] initWithNibName:#"SearchView" bundle:nil] to create your SearchViewController? I usually handle the initial view loading of my apps programmatically in the app delegate.
The error you get sounds like your IBOutlet connections are wrong somehow. Too bad you can't post a nib file here as easily as you can post code.

How can I make an view-based application that does not use a nib file?

I've choosen the "view-based" application template in Xcode. The myProjectViewController.m has the following code:
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
That sounds good. But: The template generated a myProjectViewController.xib file. What I dont get is: How does Xcode connect the ViewController with that nib? Where's the part in the template code that says: "Hey, load that myProjectViewController.xib now!"? I mean... can I just delete that not-wanted nib file without setting anything else up appropriately?
You may wish to refer to my answer to this question, where I describe the specific files that need to be altered to do completely programmatic generation of your view hierarchy.
Also, some of the references linked to in the answers to this question may be of use to you.
yep you can just delete the nib and implement that method
IB connects using the name of the class in the NIb, in IB you actually set a view as the file owner of the view. so when you call initwithnib:"nibfilename" it knows what you are talking about.
The elements are wired up using IBOutlets and IBActions

UITableView issue when using separate delegate/dataSource

General Description:
To start with what works, I have a UITableView which has been placed onto an Xcode-generated view using Interface Builder. The view's File Owner is set to an Xcode-generated subclass of UIViewController. To this subclass I have added working implementations of numberOfSectionsInTableView: tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath: and the Table View's dataSource and delegate are connected to this class via the File Owner in Interface Builder.
The above configuration works with no problems. The issue occurs when I want to move this Table View's dataSource and delegate-implementations out to a separate class, most likely because there are other controls on the View besides the Table View and I'd like to move the Table View-related code out to its own class. To accomplish this, I try the following:
Create a new subclass of UITableViewController in Xcode
Move the known-good implementations of numberOfSectionsInTableView:, tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath: to the new subclass
Drag a UITableViewController to the top level of the existing XIB in InterfaceBuilder, delete the UIView/UITableView that are automatically created for this UITableViewController, then set the UITableViewController's class to match the new subclass
Remove the previously-working UITableView's existing dataSource and delegate connections and connect them to the new UITableViewController
When complete, I do not have a working UITableView. I end up with one of three outcomes which can seemingly happen at random:
When the UITableView loads, I get a runtime error indicating I am sending tableView:cellForRowAtIndexPath: to an object which does not recognize it
When the UITableView loads, the project breaks into the debugger without error
There is no error, but the UITableView does not appear
With some debugging and having created a basic project just to reproduce this issue, I am usually seeing the 3rd option above (no error but no visible table view). I added some NSLog calls and found that although numberOfSectionsInTableView: and numberOfRowsInSection: are both getting called, cellForRowAtIndexPath: is not. I am convinced I'm missing something really simple and was hoping the answer may be obvious to someone with more experience than I have. If this doesn't turn out to be an easy answer I would be happy to update with some code or a sample project. Thanks for your time!
Complete steps to reproduce:
Create a new iPhone OS, View-Based Application in Xcode and call it TableTest
Open TableTestViewController.xib in Interface Builder and drag a UITableView onto the provided view surface.
Connect the UITableView's dataSource and delegate-outlets to File's Owner, which should already represent the TableTestViewController-class. Save your changes
Back in Xcode, add the following code to TableTestViewController.m:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(#"Returning num sections");
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"Returning num rows");
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Trying to return cell");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.text = #"Hello";
NSLog(#"Returning cell");
return cell;
}
Build and Go, and you should see the word Hello appear in the UITableView
Now to attempt to move this UITableView's logic out to a separate class, first create a new file in Xcode, choosing UITableViewController subclass and calling the class TableTestTableViewController
Remove the above code snippet from TableTestViewController.m and place it into TableTestTableViewController.m, replacing the default implementation of these three methods with ours.
Back in Interface Builder within the same TableTestViewController.xib-file, drag a UITableViewController into the main IB window and delete the new UITableView object that automatically came with it
Set the class for this new UITableViewController to TableTestTableViewController
Remove the dataSource and delegate bindings from the existing, previously-working UITableView and reconnect the same two bindings to the new TableTestTableViewController we created.
Save changes, Build and Go, and if you're getting the results I'm getting, note the UITableView no longer functions properly
Solution:
With some more troubleshooting and some assistance from the iPhone Developer Forums, I've documented a solution! The main UIViewController subclass of the project needs an outlet pointing to the UITableViewController instance. To accomplish this, simply add the following to the primary view's header (TableTestViewController.h):
#import "TableTestTableViewController.h"
and
IBOutlet TableTestTableViewController *myTableViewController;
Then, in Interface Builder, connect the new outlet from File's Owner to TableTestTableViewController in the main IB window. No changes are necessary in the UI part of the XIB. Simply having this outlet in place, even though no user code directly uses it, resolves the problem completely. Thanks to those who've helped and credit goes to BaldEagle on the iPhone Developer Forums for finding the solution.
I followed your steps, recreated the project and ran into the same problem. Basically you are almost there. There are 2 things missing (once fixed it works):
You need to connect the tableView of the TableTestTableViewController to the UITableView you have on the screen. As I said before because it is not IBOutlet you can override the tableView property and make it and IBOutlet:
#interface TableTestTableViewController : UITableViewController {
UITableView *tableView;
}
#property (nonatomic, retain) IBOutlet UITableView *tableView;
Next thing is to add a reference to the TableTestTableViewController and retain it in the TableTestViewController. Otherwise your TableTestTableViewController may be released (after loading the nib with nothing hanging on to it.) and that is why you are seeing the erratic results, crashes or nothing showing. To do that add:
#interface TableTestViewController : UIViewController {
TableTestTableViewController *tableViewController;
}
#property (nonatomic, retain) IBOutlet TableTestTableViewController *tableViewController;
and connect that in the Interface Builder to the TableTestTableViewController instance.
With the above this worked fine on my machine.
Also I think it would be good to state the motivation behind all this (instead of just using the UITableViewController with its own UITableView). In my case it was to use other views that just the UITableView on the same screenful of content. So I can add other UILabels or UIImages under UIView and show the UITableView under them or above them.
I just spent many hours pulling my hair out trying to figure out why a UITableView wouldn't show up when when I had it embedded in a separate nib instead of in the main nib. I finally found your discussion above and realized that it was because my UITableViewController wasn't being retained! Apparently the delegate and datasource properties of UITableView are not marked "retain" and so my nib was loading but the controller was getting tossed... And due to the wonders of objective-c I got no error messages at all from this... I still don't understand why it didn't crash. I know that I've seen "message sent to released xxx" before... why wasn't it giving me one of those?!?
I think most developers would assume that structure that they build in an interface builder would be held in some larger context (the Nib) and not subject to release. I guess I know why they do this.. so that the iPhone can drop and reload parts of the nib on low memory. But man, that was hard to figure out.
Can someone tell me where I should have read about that behavior in the docs?
Also - about hooking up the view. First, if you drag one in from the UI builder you'll see that they hook up the view property (which is an IBOutlet) to the table view. It's not necessary to expose the tableView, that seems to get set internally. In fact it doesn't even seem to be necessary to set the view unless you want viewDidLoad notification. I've just broken the view connection between my uitableview and uitableviewcontroller (only delegate and datasource set) and it's apparently working fine.
Yes for some reason (please chime in if anybody knows why...) tableView property of the UITableViewController is not exposed as an IBOutlet even though it is a public property. So when you use Interface Builder, you can't see that property to connect to your other UITableView. So in your subclass, you can create a tableView property marked as an IBOutlet and connect that.
This all seems hacky and a workaround to me, but it seems to be the only way to separate a UITableViewController's UITableView and put it somewhere else in UI hierarchy. I ran into the same issue when I tried to design view where there are things other than the UITableView and that was the way I solved it... Is this the right approach???
I was able to make this work. I built a really nice dashboard with 4 TableViews and a webview with video. The key is having the separate tableView controllers and the IBOutlets to the other tableview controllers defined in the view controller. In UIB you just need to connect the other tableview controllers to the file owner of the view controller. Then connect the tables to the corresponding view controllers for the datasource and delegate.