在iOS Objective-C中创建Singleton类的问题?

时间:2014-06-05 05:53:03

标签: ios objective-c singleton

我正在尝试在Objective-C中创建单例类。以下是.h和.m文件。

·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

问题是,我可以使用sharedHTTPRequest创建实例,但同时我可以调用alloc / init。那怎么保证,我的班级是单身?

1 个答案:

答案 0 :(得分:0)

如果您不希望用户调用init方法,则可以通过编写以下代码使该类的init不可用。因此,它将确保不会在该类上调用init方法。

 /*!
@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"));