【问题标题】:how to implement Singleton Pattern in my IPhone project?如何在我的 iPhone 项目中实现单例模式?
【发布时间】:2012-07-13 12:00:52
【问题描述】:

我正在做一个项目,我想使用单例模式模型。 我想要我这个项目的任何数据模型休闲单例模式。 我研究了关于这个的苹果文档

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/

现在我知道我的自定义对象类应该遵循分配对象的主要规则,但我需要完整的实现,例如使用此类对象 我是 iphone 应用程序开发的新手,所以如果我在这个问题的任何地方错了,请指导

【问题讨论】:

  • The answer 回答“你的 Objective-C 单例是什么样的?”这个问题。可能会对你有所帮助。

标签: iphone objective-c ios design-patterns singleton


【解决方案1】:

试试这个:

@implementation Singleton

+ (Singleton *)sharedInstance
{
     static Singleton *obj = nil;

    if (obj == nil)
        obj = [[self alloc] init];

    return obj;
}

@end

【讨论】:

    【解决方案2】:
    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;
    }
    

    【讨论】:

    • 你能指导我这是否适用于自定义 NSmutableArray 类?
    • 您想要一个自定义类,它是 NSMutableArray 的子类?还是具有 NSMutableArray 属性的自定义类?
    • 对不起我的错误我的意思是 nsmutableDictionary 的子类
    【解决方案3】:

    如果你可以针对iOS 4或以上,我会采取以下方式:

    //.h
    +(MySingletonClass *)mySharedInstance;
    -(void)doSomething;
    
    //.m
    +(MySingletonClass *)mySharedInstance {
        static dispatch_once_t pred;
        static MySingletonClass *shared = nil;
    
        dispatch_once(&pred, ^{
          shared = [[MySingletonClass alloc] init];
        });
        return shared;
    }
    
    -(void)doSomething
    {
    }
    
    // override also the init if you want
    

    要访问它,请执行#import MySingletonClass.h 并在任何您想要的地方使用它,如下所示:

    MySingletonClass* mySharedInstance = [MySingletonClass mySharedInstance];
    [mySharedInstance doSomething];
    

    我希望我的这个项目的任何数据模型都使用单例模式。

    根据我的经验,我不会滥用单身人士。应用程序可能会变得难以维护。为避免这种情况,请将数据模型放在单例中。您可以直接访问数据模型(围绕它们创建属性)或使用公共方法(例如doSomething)作为包装器。

    希望这会有所帮助。

    【讨论】:

      【解决方案4】:

      【讨论】:

        【解决方案5】:

        通常我在

        中创建对象
        - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
        

        方法并让它存在于该对象中。我使用宏将其提供给应用程序的其余部分:

        #define APPLICATION ((AppDelegate*)([UIApplication sharedApplication].delegate))
        

        作为应用委托的只读属性

        如果您要进行模拟,这种方法的好处是它只是另一个对象属性,而不是隐藏的静态对象。

        【讨论】:

          【解决方案6】:

          我用:

          #import <Foundation/Foundation.h>
          
          @interface iCode_Framework : NSObject
          
          @property (readonly, nonatomic) unsigned int iBufCapacity;
          @property (readonly, nonatomic) unsigned int iPort;
          @property (readonly, nonatomic) NSString * urlStr;
          
          @end
          
          #import "iCode_Framework.h"
          
          static iCode_Framework * instance;
          
          @implementation iCode_Framework
          
          @dynamic iBufCapacity;
          @dynamic iPort;
          @dynamic urlStr;
          
          - (unsigned int)iBufCapacity
          {
              return 1024u;
          };
          
          - (unsigned int)iPort
          {
              return 1978u;
          };
          
          - (NSString *)urlStr
          {
              return @"localhost";
          };
          
          + (void)initialize
          {
              if (!instance) {
                  instance = [[super allocWithZone:NULL] init];
              }
          }
          
          + (id)allocWithZone:(NSZone * const)notUsed
          {
              return instance;
          }
          
          @end
          

          它的使用与普通类完全一样,调用 alloc 和 init!分配给变量以提供简写通常很方便,因为 alloc 和 init 的类型很长,例如:

          #import "iCode_FrameworkTests.h"
          #import "iCode_Framework.h"
          
          static iCode_Framework * c;
          
          @implementation iCode_FrameworkTests
          
          + (void)initialize
          {
              c  = [[iCode_Framework alloc] init];
          }
          
          - (void)setUp
          {
              [super setUp];
          
              // Set-up code here.
          }
          
          - (void)tearDown
          {
              // Tear-down code here.
          
              [super tearDown];
          }
          
          - (void)testSingletonNotNil
          {
              STAssertNotNil(c, nil);
          }
          
          - (void)testSingletonProperty
          {
              STAssertEqualObjects(c, [iCode_Framework alloc], nil);
          }
          
          - (void)testIBufCapacity
          {
              STAssertEquals(c.iBufCapacity, 1024u, nil);
          }
          
          @end
          

          这种方法的优点是它的使用与任何其他类完全一样,因此可以模拟进行测试。

          【讨论】:

            猜你喜欢
            • 2010-12-10
            • 2022-10-16
            • 2011-09-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-15
            • 2021-04-12
            相关资源
            最近更新 更多