の下に、プロパティを持つARC
オブジェクトがあります。のいくつかのテストを作成しようとしており、 を使用してそのプロパティをモックしています。Child
weak
parent
Child
parent
OCMock
ARCではNSProxy
、合成された弱いプロパティセッターを使用してサブクラスを設定してもプロパティは設定されません...弱いプロパティが設定された後の行で、それをチェックすると、それがすでにnil
. 具体例は次のとおりです。
@interface Child : NSObject
@property (nonatomic, weak) id <ParentInterface>parent;
@end
@implementation Child
@synthesize parent = parent_;
@end
// ... later, inside a test class ...
- (void)testParentExists
{
// `mockForProtocol` returns an `NSProxy` subclass
//
OCMockObject *aParent = [OCMockObject mockForProtocol:@protocol(ParentInterface)];
assertThat(aParent, notNilValue());
// `Child` is the class under test
//
Child *child = [[Child alloc] init];
assertThat(child, notNilValue());
assertThat(child.parent, nilValue());
child.parent = (id<ParentInterface>)aParent;
assertThat([child parent], notNilValue()); // <-- This assertion fails
[aParent self]; // <-- Added this reference just to ensure `aParent` was valid until the end of the test.
}
がを参照するためにassign
プロパティの代わりにプロパティを使用してこれを回避できることはわかっていますが、それを使い終わったら (ある種の穴居人のように)をアウトする必要があります。 ARCが回避するはずだったもの。weak
Child
Parent
nil
parent
アプリのコードを変更せずにこのテストに合格する方法について何か提案はありますか?
編集: であることと関係OCMockObject
があるようです。 のインスタンスにNSProxy
すると、弱参照は nil 以外の値を「保持」します。アプリのコードを変更せずにこのテストに合格する方法をまだ探しています。aParent
NSObject
child.parent
編集 2 :ブレイクの答えを受け入れた後、条件付きでプロパティを弱いから変更するプリプロセッサ マクロのプロジェクトで実装を行いました -> 割り当て。あなたのマイレージは異なる場合があります:
#if __has_feature(objc_arc)
#define BBE_WEAK_PROPERTY(type, name) @property (weak, nonatomic) type name
#else
#define BBE_WEAK_PROPERTY(type, name) @property (assign, nonatomic) type name
#endif