iOS中的结构实现

时间:2012-08-09 05:56:21

标签: objective-c ios

SSharedAppState.h

#import <Foundation/Foundation.h>

enum {
    SharedCompletedStepNone    = 0,
    SharedCompletedStepOne     = 1 << 0,
    SharedCompletedStepTwo      = 2 << 1,
    SharedCompletedStepThree   = 3 << 2
};
typedef NSUInteger SharedCompletedSteps;

@interface SSharedAppState : NSObject
{
    struct {
        unsigned int sharedCompletedStepMask:3;
    } _appFlags;
}
@property (assign, nonatomic) SharedCompletedSteps sharedCompletedStep;

+(id)sharedInstance;
@end

SSharedAppState.m

#import "SSharedAppState.h"

#pragma mark - C functions


#pragma mark - Interface Extension

typedef struct _appFlags AppFlags;
@interface SSharedAppState ()

@property (unsafe_unretained, nonatomic) AppFlags *appFlags;
-(void *)newAppFlags;
@end

#pragma mark - Implementation

@implementation SSharedAppState
@synthesize appFlags;

#pragma mark - Iniitalizer

-(id)init
{
    self = [super init];
    if (self) {

//        appFlags = (AppFlags *)malloc(sizeof(_appFlags));
        appFlags = (AppFlags *)newAppFlags();
        appFlags->sharedCompletedStepMask = 0;
        appFlags.sharedCompletedStepMask = 0;
    }
    return self;
}

+(SSharedAppState *)sharedInstance
{
    static dispatch_once_t onceToken;
    static id sharedInstance;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

#pragma makr - Struct _appFlags

-(void *)newAppFlags
{
    AppFlags *instance = (AppFlags *)malloc(sizeof(_appFlags));
    return instance;
}


@end

问题

  1. appFlags = (AppFlags *)newAppFlags();
  2. 给出函数的隐式声明newAppFlags在C99中无效

    1. appFlags-&gt; sharedCompletedStepMask = 0; appFlags.sharedCompletedStepMask = 0;
    2. 'struct _appFlags'类型的不完整定义 成员引用类型'AppFlags *'(又名'struct _appFlags *')是一个指针;也许你打算用' - &gt;'?

      发出以下警告和错误。 这是我第一次在这里发帖,所以请提供关于HTML或编辑的建议。三江源!

1 个答案:

答案 0 :(得分:2)

当你这样写的时候

struct {
    unsigned int sharedCompletedStepMask:3;
} _appFlags;

您声明了一个未命名结构的变量_appFlags。

你可能意味着

struct _appFlags {
    unsigned int sharedCompletedStepMask:3;
};

或者你可以写

typedef struct _appFlags {
    unsigned int sharedCompletedStepMask:3;
} AppFlags;