我正在尝试在addObject:
上使用NSMutableArray
来创建我创建的类Position
。根据日志,我添加到数组的Position
实例不是nil
- 我可以将其属性输出到日志中。但是,数组似乎从未实际采用Position
。
@implementation Position
@synthesize tradeDirection, instrument, quantity, fill, profit, positive, index;
-(id)initWithArray:(NSArray*)data
{
self = [super init];
if (self)
{
self.tradeDirection = [data objectAtIndex:0];
self.instrument = [data objectAtIndex:1];
self.quantity = [data objectAtIndex:2];
self.fill = (NSNumber*)[data objectAtIndex:3];
self.profit = [data objectAtIndex:4];
self.positive = [@"True" isEqualToString:[data objectAtIndex:5]];
self.index = (NSNumber*)[data objectAtIndex:6];
}
return self;
}
+(Position*)createPositionWithString:(NSString*)data
{
return [[[self alloc] initWithArray:[data componentsSeparatedByString:@"#"]] autorelease];
}
@end
-(void)loadPositions:(NSString*)data
{
TT_RELEASE_SAFELY(_positions);
NSArray* dataArray = [data componentsSeparatedByString:@";"];
for (int i = 2; i <= [dataArray count] - 2; i++)
{
//TODO: Discover why this does not add a position.
Position* newPos = [Position createPositionWithString:[dataArray objectAtIndex:i]];
[_positions addObject:newPos]; //position never actually gets added
NSLog(@"Position direction: %@", newPos.tradeDirection); //logs what I expect, i.e. newPos is not nil
}
}
致电loadPositions:data
后,_positions
仍为nil
。很简单;我觉得这与内存管理有关,但此时我只需要第二眼。我错过了什么?
答案 0 :(得分:5)
TT_RELEASE_SAFELY宏在将其分配给nil(IIRC)之前向其参数发送释放消息。为什么_positions为零会有什么意外呢?
虽然您可能因任何原因需要释放_postitions,但您必须先分配并初始化一个新对象并将其引用分配给_positions,然后才能向其添加项目。
编辑:正如卢克在评论中指出的那样,TT_RELEASE_SAFELY来自三十二个图书馆。
#define TT_RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }