【发布时间】:2012-07-18 20:18:45
【问题描述】:
我对 iOS 5 单例有点陌生,并且正在使用此处记录的单例:
类似这样的:
MyManager.h
#import <Foundation/Foundation.h>
@interface MyManager : NSObject
//Data for section 1
@property(nonatomic,copy) NSString * section1a;
@property(nonatomic, assign) NSUInteger section1b;
//Data for section 2
@property(nonatomic,copy) NSString * section2a;
@property(nonatomic, assign) NSUInteger section2b;
+ (id)sharedInstance;
@end
MyManager.m
@implementation MyManager
@synthesize section1a, section1b, section2a; , section2b;
+ (id)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
@end
所以我使用如下:
MyManager * myManager = [MyManager sharedInstance];
myManager.data = self.data
这就是你通常使用单例的方式吗?我错过了什么吗? 对不起,我只是想确保我做对了一些基本问题。
谢谢
【问题讨论】:
-
我不确定您在 iOS 5 或其他版本中指的是哪些差异。但我认为你错过了在 .m 文件中声明这个:static MyManager *_sharedObject = nil;
-
只是为了你,你可以在你的单例类中实现这两个方法(除了
+sharedInstance方法)+allocWithZone:和+copyWithZone:,你可以添加一个static MyManager *_sharedObject;成员为你的课也是如此。 :)