I have a class RandomGenerator:
// RandomGenerator.h
#import <Foundation/Foundation.h>
@interface RandomGenerator : NSObject
{
@private
IBOutlet NSTextField* textField;
unsigned int number;
}
@end
//RandomGenerator.m
#import "RandomGenerator.h"
@implementation RandomGenerator
- (id)init
{
self = [super init];
if (self)
{
textField=[[NSTextField alloc]init];
[textField setStringValue:@"Insert a number between 1 and 100"];
srand((unsigned int)time(NULL));
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
@end
That when constructed it sets automatically the value of the NSTextField.
I allocate a RandomGenerator object from the file GuessTheNumberAppDelegate.m :
#import "GuessTheNumberAppDelegate.h"
#import "RandomGenerator.h"
@implementation GuessTheNumberAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
RandomGenerator* random=[[RandomGenerator alloc]init];
[pool drain];
}
@end
And I have made connections in interface builder:


But the content of the NSTextField is not changed, it appears the same, why this?

In
-[RandomGenerator init], you’re creating a new text field object that has no relation to the text field that’s already in your xib file, and pointing the outlet at that new object. The objects in the xib are real, actual objects that are allocated for you by the loading mechanism. You don’t needtextField = [[NSTextField alloc] init];,* nor do you needRandomGenerator* random=[[RandomGenerator alloc]init];. Both of those objects already exist in your xib.You do need to change a few things, however. First, if you want your application delegate to be able to access the
RandomGenerator, you’ll need to give it an outlet and connect it:IBOutlet RandomGenerator * generator;. Second, you will need to move[textField setStringValue:@"Insert a number between 1 and 100"];out of-[RandomGenerator init]. Due to the way nib loading works, the generator’sinitmethod will be called before theIBOutletto the text field is hooked up, and possibly before the text field is even created.I’m pretty sure that if you add:
to
RandomGenerator, that will do the trick. Once the nib has been loaded and all the objects in it are recreated,awakeFromNibshould be sent to all those objects.*and that’s not the correct initializer for an
NSTextFieldanyways