Search code examples
objective-cjailbreaktheostweakmember-variables

How to declare member variable of subclass in Theos


For example, when I declare subclass of existing class, I can write as below in theos:

%subclass NEWCLASS: EXISTINGCLASS
- (void)overridemethod {
//code
}

%new(v@:)
- (void)newmethod {
//code
}
%end

But I don't know how to declare member or property variables of new class...
What should I do?
OK, I got it.


But there are errors when I compile package..

I wrote code as below:

%subclass SBIconSubClass: SBIcon

%new
- (NSString *)aString {
    return objc_getAssociatedObject(self, @selector(aString));
}

%new
- (void)setAString:(NSString *)value {
    objc_setAssociatedObject(self, @selector(aString), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)application {
    self.aString = @"Test";
    NSLog(@"%@",self.aString);

    return %orig;
}

%end

and error:

enter image description here


Solution

  • You can't, ivars are not supported. What you can do is simulate properties, using objc_getAssociatedObject and objc_setAssociatedObject.

    %new
    - (BOOL)boolProp {
        NSNumber * _boolProp = objc_getAssociatedObject(self, @selector(boolProp));
        return _boolProp ? [_boolProp boolValue] : NO;
    }
    
    %new
    - (NSString *)aString {
        return objc_getAssociatedObject(self, @selector(aString));
    }
    
    %new
    - (void)setBoolProp:(BOOL)value {
        objc_setAssociatedObject(self, @selector(boolProp), @(value), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    %new
    - (void)setAString:(NSString *)value {
        objc_setAssociatedObject(self, @selector(aString), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    

    This way you can access boolProp and aString as a properties:

    inst.boolProp = YES;
    if (inst.boolProp) {
        ...
    }
    
    inst.aString = @"Hello";
    

    In your example you also need to define an interface:

    @interface SBIconSubClass
        - (NSString *)aString;
        - (void)setAString:(NSString *)value;
    @end