Accessing an Objective C ivar without a @property or a getter method?

时间:2015-08-07 01:52:54

标签: objective-c cocoa

Is there any way to access an instance variable on an Objective C object without using @property or a getter method?

I've got a class here that needs to be able to "merge" itself with another object of the same class. The problem is that I need to be able to access the ivars of the "other" object in order to merge it with the current object, but I don't want to declare those ivars as a property or implement some other getter method, because I don't want anybody thinking that they should be fiddling with those ivars in any way.

Once again, I don't need to access the ivars from any other class other then that class itself. As an example, here's what I'm looking to do:

@interface MySillyObject : NSObject
{
    double _someCounter;
}

@implementation

+ (MySillyObject *)sillyObjectWithCounter:(double)counter
{
    return [[[MySillyObject alloc] initWithCounter:counter] autorelease];
}

- (id)initWithCounter:(double)counter
{
    if (self = [super init]) {
        _someCounter = counter;
    }
}

- (MySillyObject *)mergeWithOtherObject:(MySillyObject *)otherObject
{
    // What do I do here?
    // I need to return _someCounter + otherObject's _someCounter...
    return [MySillyObject sillyObjectWithCounter:???];
}

1 个答案:

答案 0 :(得分:0)

You can actually sidestep ivar access policy for pretty much any Cocoa object with valueForKey:; if you know the name of the property or the ivar, KVC will root around in the class's internals and retrieve the value for you.

But in this case, you don't even need to do that. Since otherObject is a member of the same class, you can access it directly: otherObject->_someCounter. You can in fact access it within the same class for any level of visibility, even if you declare it in the recommended "very private" @implementation block.

相关问题