我有點新的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; – 2012-07-19 15:45:54
只是爲了你,你可以在你的單例類(除了'+ sharedInstance'方法)'+ allocWithZone:'和'+ copyWithZone:'實現這兩個方法,並且你可以添加一個'MyManager * _sharedObject'成員也適合你的班級。 :) – holex 2012-07-19 15:51:43