0
,我有以下结构如何在obj C中使用并访问结构值作为属性?获取EXEC坏访问
Helper.h
typedef struct fileInfo {
UInt8 *fileHeaderContent;
UInt32 fileHeaderLength;
}
typedef struct globalFileStruct {
UInt8 *data;
UInt32 dataLength;
fileInfo fp;
}
我需要用这个作为我单身的部分内容如下:
@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
就像我在代码中指出的那样,我越来越一个错误的访问错误,我推测因为gFileInfo是NULL。
我的问题是,处理这种情况的最佳方法是什么?我怎样才能确保指针对象指向一个真实的,而不是NULL的变量?
我最初试图具有代码是:
@property (nonatomic, assign) globalFileStruct gFileInfo;
然而,当我的方法中使用它这样做的问题如下:
file.gFileInfo->fp.fileHeaderContent = [somedata bytes]
我得到了错误:"Expression not assignable"
'gFileInfo'为空。您正在存储一个指向结构的指针。你从来没有给过这个指针除null以外的任何值。 – jtbandes
您将需要'malloc'结构的一些内存并将其分配给指针。 – Paulw11
@ Paulw11如果我在init和free的dealloc中做了malloc,当进程被终止时是否会自动调用dealloc,或者我应该显式调用dealloc? – ExceptionHandler