I'm sure this is going to sound very weird, but I'll ask anyway. I have made multiple working applications for the iPhone, but I have to add everything to the original view controller. If I don't do so, the app crashes. Here is my example:
In the view controller:
- (IBAction) someAction: (id) sender {
NSLog(@"lajkrbgl");
}
This works just fine. But, if I do the "Add File" and I choose "Objective-C Class", and put the same code in, the app just crashes whenever I press the button. How can I add more objects and have them function like they do for OS X?
EDIT: Below are the steps I took to make the new object. These steps worked for me when making an OS X application.
After that, I clicked the button, and the application quit (almost as if i clicked the Home button). I did not get any errors. I then decided that it was because I didn't put the code in for the action, so I did that next.
- (IBAction) someAction: (id) sender; {
NSLog(@"lajkrbl");
}
Even after this, it crashed in the exact same way, and without an error message. Can anybody see what I did wrong?
EDIT2: I just got Xcode 4 running, and when I clicked the button, it told me that this code is giving me the problem (I put "**" before the line that had the green line).
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
**int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
How in the world did that go wrong? That is created by Xcode when I make projects!
It is indeed different in iOS. This note in the View Controller Programming Guide:
Whenever you add objects to the top-level of your nib file, you should always connect those objects to outlets somewhere else in the nib file. [...] because top-level objects are retained and then autoreleased, if you did not retain the object, it might possibly be released before you had a chance to use it.
and, more definitively, Table 1-1 in the Resource Programming Guide:
Objects in the nib file are created with a retain count of 1 and then autoreleased. [...] If you define outlets for nib-file objects, you should always define a setter method (or declared property) for accessing that outlet. Setter methods for outlets should retain their values, and setter methods for outlets containing top-level objects must retain their values to prevent them from being deallocated.
both indicate that you should add an IBOutlet
for the object which implements the button's action method to your view controller, and have the view controller retain that object (a property makes this easy):
@interface ButtonCrashViewController : UIViewController {
IBOutlet ButtonActioner * myButtonActioner;
}
@property (retain, nonatomic) IBOutlet ButtonActioner *myButtonActioner;
@end
In ButtonActioner.m:
- (IBAction)someAction:(id)sender {
NSLog(@"This didn't crash!");
}
You then hook the view controller's outlet and the button's action up as usual in Interface Builder.