实例变量不存在时,屏蔽错误问题


#1

下面修改实例变量 _width,如果_width不存在时,如何判断呢,才能不报错误呢?

double &iwidth(MSHookIvar<double>(myins, "_width"));
iwidth=5.0;

我偿试这样:

 double &iwidth(MSHookIvar<double>(myins, "_width"));
if (&tscale!=nil) 
{
	 tscale=5.0;
}

但是编译报错:
reference cannot be bound to dereferenced null pointer
in well-defined C++ code; comparison may be assumed to always evaluate to
true [-Werror,-Wtautological-undefined-compare]
if (&tscale!=nil)


#2
template <typename Type_>
static inline Type_ &MSHookIvar(id self, const char *name) {
    Ivar ivar(class_getInstanceVariable(object_getClass(self), name));
#if __has_feature(objc_arc)
    void *pointer(ivar == NULL ? NULL : reinterpret_cast<char *>((__bridge void *)self) + ivar_getOffset(ivar));
#else
    void *pointer(ivar == NULL ? NULL : reinterpret_cast<char *>(self) + ivar_getOffset(ivar));
#endif
    return *reinterpret_cast<Type_ *>(pointer);
}
void *pointer = ivar == NULL ? NULL : xxx;
*reinterpret_cast<Type_ *>(NULL);   // pointer  == NULL

不存在的话你应该已经崩了


#3

多谢老师,搞定了