Re: Creating shared classes
Re: Creating shared classes
- Subject: Re: Creating shared classes
- From: Brendan Younger <email@hidden>
- Date: Wed, 18 Jul 2001 12:46:54 -0500
This is what you really want to do. Notice especially the change in
-sharedUserSession. Also, a mutable string was not necessary since you
are changing it without modifying it once it's changed. May I strongly
suggest you read some of the memory related articles on
www.stepwise.com/Articles/.
/// main.m
#import <Cocoa/Cocoa.h>
#import "UserSession.h"
int main(int argc, const char *argv[])
{
[[UserSession sharedUserSession] setUsername:@"Lord Storm"];
NSLog([[UserSession sharedUserSession] Username]); // Always prints
out blank text
return NSApplicationMain(argc, argv);
}
/// UserSession.h
#import <Cocoa/Cocoa.h>
@interface UserSession : NSObject {
NSString* sessionUsername;
}
+ (UserSession*)sharedUserSession;
- (NSMutableString*)Username;
- (void)setUsername:(NSString*)newUsername;
@end
/// UserSession.m
#import "UserSession.h"
static UserSession* mainUserSession = nil;
@implementation UserSession
- (id)init {
return [super init];
}
+ (UserSession*)sharedUserSession {
if(mainUserSession == nil)
{
mainUserSession = [[UserSession alloc] init];
}
return mainUserSession;
}
- (NSString*)Username {
return sessionUsername;
}
- (void)setUsername:(NSString*)newUsername {
NSLog(@"Got goodness");
//note the order of these retains and releases. you must do it in
this order because newUsername may be the same object as sessionUsername
[newUsername retain];
[sessionUsername release];
sessionUsername = newUsername;
}
@end
Brendan Younger