Ios 如何将结构值作为obj C中的属性使用和访问?获取exec错误访问权限

Ios 如何将结构值作为obj C中的属性使用和访问?获取exec错误访问权限,ios,objective-c,struct,exc-bad-access,Ios,Objective C,Struct,Exc Bad Access,我有以下结构 Helper.h typedef struct fileInfo { UInt8 *fileHeaderContent; UInt32 fileHeaderLength; } typedef struct globalFileStruct { UInt8 *data; UInt32 dataLength; fileInfo fp; } 我需要将其作为我的singleton的一部分,如下所示: @interface CommonFil

我有以下结构

Helper.h

typedef struct fileInfo {
    UInt8 *fileHeaderContent;
    UInt32 fileHeaderLength;

}

typedef struct globalFileStruct {
    UInt8 *data;
    UInt32 dataLength;
    fileInfo fp;
} 
我需要将其作为我的singleton的一部分,如下所示:

@interface CommonFile : NSObject

+ (instancetype)sharedInstance;
@property (nonatomic, assign) globalFileStruct *gFileInfo;

@end

@implementation CommonFile

+ (instancetype)sharedInstance
{
    static CommonFile *sharedInfo = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInfo = [[self alloc] init];
    });
    return sharedInfo;
}

-(void)someMethod {
   CommonFile *file = [CommonFile sharedInstance];

   /* BAD ACCESS ERR */
   if( file.gFileInfo->fp.fileHeaderContent == NULL) {

        //do something
   }
}
@end
 file.gFileInfo->fp.fileHeaderContent = [somedata bytes]
正如我在代码中指出的,我得到了一个糟糕的访问错误,我认为这是因为gFileInfo为NULL

我的问题是,处理这种情况的最佳方式是什么?如何确保指针对象指向一个实变量而不是空变量

我最初尝试将代码设置为:

@property (nonatomic, assign) globalFileStruct gFileInfo;
但是,问题是我在以下方法中使用它:

@interface CommonFile : NSObject

+ (instancetype)sharedInstance;
@property (nonatomic, assign) globalFileStruct *gFileInfo;

@end

@implementation CommonFile

+ (instancetype)sharedInstance
{
    static CommonFile *sharedInfo = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInfo = [[self alloc] init];
    });
    return sharedInfo;
}

-(void)someMethod {
   CommonFile *file = [CommonFile sharedInstance];

   /* BAD ACCESS ERR */
   if( file.gFileInfo->fp.fileHeaderContent == NULL) {

        //do something
   }
}
@end
 file.gFileInfo->fp.fileHeaderContent = [somedata bytes]
我得到了错误:
“表达式不可赋值”

我得到了错误:“表达式不可赋值”


将整个结构构造为局部变量,替换字段并将其指定给属性。结构非常重,可以通过值作为参数传递。

gFileInfo
为空。您正在存储指向结构的指针。您从未为该指针指定过除null以外的任何值。您需要为结构体
malloc
一些内存并将其分配给指针。@Paulw11如果我在init中使用malloc并在dealloc中使用free,当进程终止时会自动调用dealloc吗?还是应该显式调用dealloc?因为它是一个单例,它永远不会被释放,但当应用程序退出时,一切都会在那时为你清理干净。就我个人而言,我不会使用这样的结构;我只会在需要时(例如,当与需要该结构的C函数交互时)使用一个类并创建该结构的实例@Paulw11这只是个人偏好还是以这种方式使用它有问题?