如何在我的iPhone项目中实现Singleton Pattern? [英] how to implement Singleton Pattern in my IPhone project?

查看:126
本文介绍了如何在我的iPhone项目中实现Singleton Pattern?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开展一个项目,我想使用Singleton Pattern模型。
我想要我的这个项目的任何数据模型休闲Singleton模式。
i研究关于这个的苹果文档

i am working on a project in wich i want to use Singleton Pattern model. i want to any data model of my this project fallow Singleton Pattern. i study the apple documentation regarding this

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ CocoaFundamentals / CocoaDesignPatterns / CocoaDesignPatterns.html#// apple_ref / doc / uid / TP40002974-CH6-SW6

http://www.oodesign.com/singleton-pattern.html

http://www.daveoncode.com/2011/12/19/fundamental-ios-design-patterns-sharedinstance-singleton-objective-c/

现在我知道我的自定义对象类应该放弃一个对象的主要规则,但是我需要完成e实现就像使用这个类对象
i am new在iphone应用程序开发中,所以如果我在这个问题的任何地方错了,请指导

now i know my custom object classes should fallow the main rule of allocing a object but the i need the complete implementation like using of this class object i am new in iphone app development so if i am wrong in any place in this Question please guide

推荐答案

static MyClass *_sharedInstance;

+ (MyClass *)sharedMyClass
{
    @synchronized([MyClass class]) {
        if (_sharedInstance == nil)
            [[self alloc] init];

        return _sharedInstance;
    }

    return nil;
}

+(id) alloc
{
    @synchronized([MyClass class]) {
        NSAssert(_sharedInstance == nil, @"Attempted to allocate a second instance of MyClass.");
        _sharedInstance = [super alloc];
        return _sharedInstance;
    }

    return nil;
}

+ (id) allocWithZone:(NSZone *)zone 
{
    @synchronized([MyClass class]) {
        NSAssert(_sharedInstance == nil, @"Attempted to allocate a second instance of MyClass.");
        _sharedInstance= [super allocWithZone:zone];
        return _sharedInstance;
    }
    return nil; //on subsequent allocation attempts return nil
}

- (id) copyWithZone:(NSZone *)zone 
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;
}

- (oneway void)release
{
    // Do nothing
}

- (id)autorelease
{
    return self;
}

这篇关于如何在我的iPhone项目中实现Singleton Pattern?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆