NSMutableArray addObject不添加对象,并且对象IS已分配

zkw*_*ntz 0 cocoa-touch objective-c nsmutablearray ios

我试图使用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
Run Code Online (Sandbox Code Playgroud)

loadPositions:数据方法

-(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
    }
}
Run Code Online (Sandbox Code Playgroud)

打电话后loadPositions:data,_positions仍然是nil.很简单; 我觉得这与内存管理有关,但此时我只需要第二眼.我错过了什么?

Col*_*n S 5

TT_RELEASE_SAFELY宏在将其分配给nil(IIRC)之前向其参数发送释放消息.为什么_positions为零会有什么意外?

虽然您可能因任何原因需要释放_postitions,但您必须先分配并初始化一个新对象,并在向其添加项目之前将其引用分配给_positions.

编辑:正如卢克在评论中指出的那样,TT_RELEASE_SAFELY来自三十二库.

#define TT_RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }
Run Code Online (Sandbox Code Playgroud)

  • 这个.我可以补充一点,如果使用非标准库代码(例如TT_RELEASE_SAFELY,是来自Three20库吗?),它有助于解释它的作用.并非所有人都使用这些库. (2认同)
  • 是的,及时编程范例经典的将对象设置为nil导致对象为零. (2认同)