简体   繁体   中英

Problem creating Singleton class in iOS Objective-C?

I am trying to create singleton class in Objective-C. following is .h and .m file.

.h

#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperationManager.h"

@interface LGHTTPRequest : AFHTTPRequestOperationManager

-(instancetype)sharedHTTPRequest;

-(void)postWithUrl:(NSString*)url parameter:(NSDictionary*)parameters;
@end

.m

#import "LGHTTPRequest.h"

static NSString* BaseURLString = @"someurl";

@implementation LGHTTPRequest

-(instancetype)sharedHTTPRequest
{
    static LGHTTPRequest *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[LGHTTPRequest alloc] initWithBaseURL:[NSURL URLWithString:BaseURLString]];

        _sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
        [_sharedClient.securityPolicy setAllowInvalidCertificates:YES];
        _sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/x-json"];
    });

    return _sharedClient;
}


-(void)postWithUrl:(NSString *)url parameter:(NSDictionary *)parameters
{
    //implemented but no need to show here
}

@end

Problem is, I can create instance using sharedHTTPRequest , but at same time I can call alloc/init. Then how to ensure, my class is singleton?

If you don't want the user to call the init method then you can make the init of that class unavailable by writing following code. So it will make sure that the init method will not be called on that class.

 /*!
@method init

@abstract Should create only one instance of class. Should not call init.

*/

- (id)init __attribute__((unavailable("init is not available in yourClassName, Use sharedManager"));

/*!
@method new

@abstract Should create only one instance of class. Should not call new.

*/

+ (id)new __attribute__((unavailable("new is not available in yourClassName, Use sharedManager"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM