clement
clement

Reputation: 4266

problem with singleton's methods in Objective-C

I'm doing singleton and A cannot use methods on it... the type for arguments is not right apparently... and there are lots of mistakes (errors)...

Errors are in comment (in the code)

In a foreign Class :

[ [MySingleton sharedMySingleton] setAuth:@"test"]; //incompatible type for argument 1 of setAuth
NSLog([ [MySingleton sharedMySingleton] getAuth]); //Incompatible type for argument 1 os NSLOG

In my singleton's Classes :

#import <Foundation/Foundation.h>


@interface MySingleton : NSObject {

    NSString *myToken;

}

+(MySingleton*)sharedMySingleton;

-(void)setAuth:(NSString) token;
-(NSString)getAuth;

@property (nonatomic, retain) NSString *myToken;

@end

... and ...

    #import "MySingleton.h"

@implementation MySingleton

static MySingleton* _sharedMySingleton = nil;
@synthesize myToken;

+(MySingleton*)sharedMySingleton
{
    @synchronized([MySingleton class])
    {
        if (!_sharedMySingleton)
            [[self alloc] init];

        return _sharedMySingleton;
    }

    return nil;
}

+(id)alloc
{
    @synchronized([MySingleton class])
    {
        NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
        _sharedMySingleton = [super alloc];
        return _sharedMySingleton;
    }

    return nil;
}

-(id)init {
    self = [super init];
    if (self != nil) {
        // initialize stuff here
    }

    return self;
}

-(void)setAuth:(NSString) token { // Can not use as abject as parameter to a method
    myToken=token;// incomatible types in assignment
}

-(NSString)getAuth { // can not use an object as parameter to a method
    return myToken;// incomatible types in return
} // control reaches end of non-void function


@end

Upvotes: 0

Views: 305

Answers (3)

Felix
Felix

Reputation: 35384

Replace NSString with NSString* everywhere.

Upvotes: 1

odrm
odrm

Reputation: 5259

Your header file is missing the * for the NSString type. For example, it should be :

-(void)setAuth:(NSString *) token;

Upvotes: 1

JeremyP
JeremyP

Reputation: 86651

-(void)setAuth:(NSString) token;
-(NSString)getAuth;

should be

-(void)setAuth:(NSString*) token;
//                      ^ note a pointer is needed
-(NSString*)getAuth;
//        ^ note a pointer is needed

Also, your alloc is crazy. You actually invoke [super alloc] which will give you an object of the wrong type. Check out how to implement singleton in objective-c for iphone for better ways to do singletons.

Upvotes: 4

Related Questions