I understand that in Objective C 'instance variables are always initialized to 0 (or nil, NULL, or false, depending on the exact data type)'. stackoverflow question
In the unit test2 below, why is the instance variable _willBeRipeBy
in the orange instance of Fruit
not set to nil
? It fails at STAssertNil([orange willBeRipeBy],nil)
.
test2
passes if I create an init
method to explicitatly set _willBeRipeBy
to nil or if I rename test1
to test3 to change the execution order.
Creating apple
in test1
seems to be effecting the memory that orange
uses but why is Fruits init
not resetting the instance variable to nil.
I am new to objective C, Thanks.
(using Xcode 4.3, iOS5.0 with Automatic Reference Counting on)
@interface Fruit : NSObject
- (NSDate *)getWillBeRipeBy;
- (void)setWillBeRipeBy:(NSDate *)ripeBy;
@end
@implementation Fruit
NSDate *_willBeRipeBy;
- (NSDate *)getWillBeRipeBy{
return _willBeRipeBy;
}
- (void)setWillBeRipeBy:(NSDate *)ripeBy{
_willBeRipeBy = ripeBy;
}
@end
@implementation TestIvarInitialisationTests
- (void)test1
{
Fruit *apple = [[Fruit alloc] init];
STAssertNil([apple getWillBeRipeBy],nil);
NSDate * now = [NSDate date];
[apple setWillBeRipeBy:now];
STAssertEqualObjects([apple getWillBeRipeBy], now,nil);
}
- (void)test2
{
Fruit *orange = [[Fruit alloc] init];
STAssertNil([orange getWillBeRipeBy],nil);
}
@end