问题描述
|
我试图在具有我创建的类
Position
的NSMutableArray
上使用addobject:
。根据日志,我要添加到数组的“ 2”实例不是“ 4”-我可以将其属性输出到日志。但是,该数组似乎从未实际取2。
@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
loadPositions:data方法
-(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
。非常简单;我感觉这与内存管理有关,但是在这一点上,我只需要再看一眼即可。我想念什么?
解决方法
TT_RELEASE_SAFELY宏在将其分配为nil(IIRC)之前,先向其参数发送释放消息。 _positions为零为什么会感到惊讶?
尽管出于某种原因可能需要释放_postitions,但必须先分配和初始化一个新对象,然后将其引用分配给_positions,然后才能向其中添加项目。
编辑:正如卢克(Luke)在其评论中指出的那样,TT_RELEASE_SAFELY来自three20库。
#define TT_RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }