Object-C实现单例模式
头文件:
@interface PlotGallery : NSObject
{
NSMutableArray *plotItems;
}
+(PlotGallery *)sharedPlotGallery;
-(void)addPlotItem:(PlotItem *)plotItem;
-(void)sortByTitle;
-(NSUInteger)count;
-(PlotItem *)objectAtIndex:(NSUInteger)index;
@end
实现文件:
#import "PlotGallery.h"
@implementation PlotGallery
static PlotGallery *sharedPlotGallery = nil;
+(PlotGallery *)sharedPlotGallery
{
@synchronized(self)
{
if ( sharedPlotGallery == nil ) {
sharedPlotGallery = [[selfalloc] init];
}
}
returnsharedPlotGallery;
}
+(id)allocWithZone:(NSZone *)zone
{
@synchronized(self)
{
if ( sharedPlotGallery == nil ) {
return [super allocWithZone:zone];
}
}
returnsharedPlotGallery;
}
-(id)init
{
Class thisClass = [self class];
@synchronized(thisClass)
{
if ( sharedPlotGallery == nil ) {
if ( (self = [super init]) ) {
sharedPlotGallery = self;
plotItems = [[NSMutableArray alloc] init];
}
}
}
returnsharedPlotGallery;
}
-(id)copyWithZone:(NSZone *)zone
{
returnself;
}
-(id)retain
{
returnself;
}
-(NSUInteger)retainCount
{
returnUINT_MAX;
}
-(oneway void)release
{
}
-(id)autorelease
{
returnself;
}
-(void)addPlotItem:(PlotItem *)plotItem
{
[plotItems addObject:plotItem];
}
-(NSUInteger)count
{
return [plotItemscount];
}
-(PlotItem *)objectAtIndex:(NSUInteger)index
{
return [plotItemsobjectAtIndex:index];
}
-(void)sortByTitle
{
[plotItems sortUsingSelector:@selector(titleCompare:)];
}
@end

浙公网安备 33010602011771号