代码之家  ›  专栏  ›  技术社区  ›  codemonkey

在singleton中设置nsmutabledictionary条目?

  •  0
  • codemonkey  · 技术社区  · 14 年前

    我正在使用一个singleton来存储应用程序状态信息。我将singleton包含在一个实用程序类中(最终还有其他东西)。该实用程序类依次包含在各种视图控制器等中并从中使用。实用程序类的设置如下:

    // Utilities.h
    #import <Foundation/Foundation.h>
    
    @interface Utilities : NSObject {
    
    }
    
    + (id)GetAppState;
    - (id)GetAppDelegate;
    
    @end
    
    // Utilities.m
    #import "Utilities.h"
    #import "CHAPPAppDelegate.h"
    #import "AppState.h"
    
    @implementation Utilities
    
    CHAPPAppDelegate* GetAppDelegate() {
        return (CHAPPAppDelegate *)[UIApplication sharedApplication].delegate;
    }
    
    AppState* GetAppState() {
        return [GetAppDelegate() appState];
    }
    
    @end
    

    …AppState Singleton如下所示:

    // AppState.h
    #import <Foundation/Foundation.h>
    @interface AppState : NSObject {
        NSMutableDictionary *challenge;
        NSString  *challengeID;
    }
    @property (nonatomic, retain) NSMutableDictionary *challenge;
    @property (nonatomic, retain) NSString *challengeID;
    + (id)appState;
    @end
    
    // AppState.m
    #import "AppState.h"
    
    static AppState *neoAppState = nil;
    
    @implementation AppState
    @synthesize challengeID;
    @synthesize challenge;
    
    # pragma mark Singleton methods
    + (id)appState {
        @synchronized(self) {
            if (neoAppState == nil)
                [[self alloc] init];
        }
        return neoAppState;
    }
    
    + (id)allocWithZone:(NSZone *)zone {
        @synchronized(self) {
            if (neoAppState == nil) {
                neoAppState = [super allocWithZone:zone];
                return neoAppState;
            }
        }
        return nil;
    }
    
    - (id)copyWithZone:(NSZone *)zone {
        return self;
    }
    
    - (id)retain {
        return self;
    }
    
    - (unsigned)retainCount {
        return UINT_MAX; //denotes an object that cannot be released
    }
    
    - (void)release {
        // never release
    }
    
    - (id)init {
        if (self = [super init]) {
            challengeID = [[NSString alloc] initWithString:@"0"];
            challenge = [NSMutableDictionary dictionary];
        }
        return self;
    }
    
    - (void)dealloc {
        // should never be called, but just here for clarity
        [super dealloc];
    }
    @end
    

    …然后,从一个视图控制器,我可以这样设置singleton的“challengeid”属性:

    [GetAppState() setValue:@"wassup" forKey:@"challengeID"];
    

    …但当我尝试设置“挑战”字典条目值时,如下所示:

    [[GetAppState() challenge] setObject:@"wassup" forKey:@"wassup"];
    

    …它无法给我一个“已发送无法识别的选择器…”错误。如有任何见解/建议,将不胜感激。

    1 回复  |  直到 14 年前
        1
  •  3
  •   Georg Fritzsche    14 年前

    在你 -init 方法,应将保留字典分配给ivar:

    challenge = [[NSMutableDictionary alloc] init];