单身整数问题

时间:2010-10-16 18:36:29

标签: iphone objective-c singleton int

我有一个单身,我拿着一个整数,我的分数。然而,当我在另一个视图中加载它时,它没有显示我想要的东西,而是坚持使用有线6592960.任何想法为什么?与我如何使用@property有关我想,@property和int的正确方法是什么?

感谢。

编辑: 码: Singleton .h

#import <Foundation/Foundation.h>


@interface scoreData : NSObject {

    int score;
}

@property int score;

+ (scoreData *)sharedData;

@end

Singleton .m

#import "scoreData.h"


static scoreData *sharedData = nil;

@implementation scoreData

@synthesize score;

#pragma mark -
#pragma mark Singleton Methods
+ (scoreData *)sharedData {
    if(sharedData == nil){
        sharedData = [[super allocWithZone:NULL] init];
    }
    return sharedData;
}
+ (id)allocWithZone:(NSZone *)zone {
    return [[self sharedManager] retain];
}
- (id)copyWithZone:(NSZone *)zone {
    return self;
}
- (id)retain {
    return self;
}
- (unsigned)retainCount {
    return NSUIntegerMax;
}
- (void)release {
    //do nothing
}
- (id)autorelease {
    return self;
}

@end

在我的其他视图中,我这样访问,然后尝试更改数字,当然我导入单例:

scoreData *score = [scoreData sharedData];
score.score = 0;

3 个答案:

答案 0 :(得分:0)

如果它是一个真正的单例,那么你可以让你的getter和setter直接访问一个初始化的静态全局变量,并跳过所有运行时alloc和zone busywork。

答案 1 :(得分:0)

我会像这样写@property

@property (nonatomic,assign) int score;

我也会改变sharedData

+ (scoreData *)sharedData {
    if( sharedData == nil ){
        sharedData = [[self alloc] init];
    }
    return sharedData;
}

编辑:我尝试了你的代码并获得了EXC_BADACCESS,因为它在这里递归:

+ (id)allocWithZone:(NSZone *)zone {
    return [[self sharedManager] retain];
}

当我删除该方法时,一切都按预期工作。

答案 2 :(得分:0)

MySingleton.h

#import <Foundation/Foundation.h>

@interface MySingleton : NSObject {

}
@property(nonatomic,assign) int score;
+ (MySingleton*) sharedInstance;

@end

MySingleton.m

#import "MySingleton.h"

static MySingleton *_instance;
@implementation MySingleton
@synthesize score;

+ (MySingleton*)sharedInstance
{
    @synchronized(self) {
        if (_instance == nil) {
            _instance = [[super allocWithZone:NULL] init];
        }
    }
    return _instance;
}

#pragma mark Singleton Methods
+ (id)allocWithZone:(NSZone *)zone
{   
    return [[self sharedInstance]retain];   
}

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

- (id)retain
{   
    return self;    
}

- (unsigned)retainCount
{
    return NSUIntegerMax; 
}

- (void)release
{
}

- (id)autorelease
{
    return self;    
}

@end

请参阅此xcode-template以简化单例生成。