[英]Problem creating Singleton class in iOS Objective-C?
I am trying to create singleton class in Objective-C. 我正在尝试在Objective-C中创建单例类。 following is .h and .m file.
以下是.h和.m文件。
.h 。H
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperationManager.h"
@interface LGHTTPRequest : AFHTTPRequestOperationManager
-(instancetype)sharedHTTPRequest;
-(void)postWithUrl:(NSString*)url parameter:(NSDictionary*)parameters;
@end
.m .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. 问题是,我可以使用
sharedHTTPRequest
创建实例,但是同时我可以调用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. 如果您不希望用户调用
init
方法,则可以通过编写以下代码来使该类的init
不可用。 So it will make sure that the init
method will not be called on that class. 因此,它将确保不会在该类上调用
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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.