issues make a persistent object in Objective C

Posted by oden on Stack Overflow See other posts from Stack Overflow or by oden
Published on 2010-03-08T14:51:33Z Indexed on 2010/03/08 15:36 UTC
Read the original article Hit count: 686

Attempting to make a NSObject called 'Person' that will hold the login details for my application (nothing to fancy). The app is made of a navigation controller with multiple table views but I am having issues sharing the Person object around.

Attempted to create a static object like this:

+ (Person *)sharedInstance {
    static Person *sharedInstance;
    @synchronized(self) {
        if(!sharedInstance)
            sharedInstance = [[Person alloc] init];
        return sharedInstance;
    }
    return nil;
}

And here is the header

// Person.h
#import <Foundation/Foundation.h>

@interface Person : NSObject {

    NSString    *fullName;
    NSString    *firstName;
    NSString    *lastName;
    NSString    *mobileNumber;
    NSString    *userPassword;
}

@property(nonatomic, retain) NSString   *fullName;
@property(nonatomic, retain) NSString   *firstName;
@property(nonatomic, retain) NSString   *lastName;
@property(nonatomic, retain) NSString   *mobileNumber;
@property(nonatomic, retain) NSString   *userPassword;

+ (Person *)sharedInstance;
-(BOOL) setName:(NSString*) fname;
-(BOOL) setMob:(NSString*) mnum;
-(BOOL) setPass:(NSString*) pwd;

@end

This object setters and getters are needed in different parts of the application. I have been attempting to access them like this

Person * ThePerson = [[Person alloc] init];
ThePerson = nil;
NSString * PersonsName;
PersonsName = [[Person sharedInstance] firstName];

Everything works well at the login screen but it dies at the next use. usually EXC_BAD_ACCESS (eek!).

Clearly I am doing something very wrong here. Is there an easier way to share objects between different a number view controllers (both coded and xib)?

© Stack Overflow or respective owner

Related posts about iphone-sdk

Related posts about objective-c