ios之objective-c -单例实现示例

artech 阅读:34 2025-05-04 20:05:19 评论:0

*我肯定需要休息一下...原因很简单-未分配数组...感谢您的帮助。由于这个尴尬的错误,我标记了我的帖子以将其删除。我认为这对用户没有帮助;)*

我刚刚尝试在iOS中创建一个单例类,但是我可能会犯一个错误。代码(不需要ARC):

#import "PeopleDatabase.h" 
#import "Person.h" 
 
#import <Foundation/Foundation.h> 
 
@interface PeopleDatabase : NSObject{objetive 
    NSMutableArray* _arrayOfPeople; 
} 
 
+(PeopleDatabase *) getInstance; 
 
@property (nonatomic, retain) NSMutableArray* arrayOfPeople; 
 
 
@end 

-
    @implementation PeopleDatabase 
    @synthesize arrayOfPeople = _arrayOfPeople; 
 
    static PeopleDatabase* instance = nil; 
 
    -(id)init{ 
        if(self = [super init]) { 
            Person* person = [[[Person alloc] initWithName:@"John" sname:@"Derovsky" descr:@"Some kind of description" iconName:@"johnphoto.png" title:Prof] retain]; 
 
            [_arrayOfPeople addObject:person]; 
            NSLog(@"array count = %d", [_arrayOfPeople count]); // <== array count = 0  
            [person release]; 
        } 
        return self; 
    } 
 
    +(PeopleDatabase *)getInstance { 
        @synchronized(self) 
        { 
            if (instance == nil) 
                NSLog(@"initializing"); 
                instance = [[[self alloc] init] retain]; 
                NSLog(@"Address: %p", instance); 
        } 
        return(instance); 
    } 
 
    -(void)dealloc { 
 
        [instance release]; 
        [super dealloc]; 
    } 
@end 

当像这样调用getInstance时:
PeopleDatabase *database = [PeopleDatabase getInstance]; 
NSLog(@"Adress 2: %p", database); 

地址2的值与getInstance中的值相同。

请您参考如下方法:

创建单例的标准方法是...

单例

@interface MySingleton : NSObject 
 
+ (MySingleton*)sharedInstance; 
 
@end 

单例
#import "MySingleton.h" 
 
@implementation MySingleton 
 
#pragma mark - singleton method 
 
+ (MySingleton*)sharedInstance 
{ 
    static dispatch_once_t predicate = 0; 
    __strong static id sharedObject = nil; 
    //static id sharedObject = nil;  //if you're not using ARC 
    dispatch_once(&predicate, ^{ 
        sharedObject = [[self alloc] init]; 
        //sharedObject = [[[self alloc] init] retain]; // if you're not using ARC 
    }); 
    return sharedObject; 
} 
 
@end 


标签:ios
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号