开发者

NSMutableArray addObject not adding objects, and object IS allocated

I'm trying to use addObject: on an NSMutableArray with a class I've created, called Position. According to the logs, the Position instance that I am adding to the array is not nil -- I can output its properties to the log. However, the array never seems to actually take the 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

loadPositions:data method

-(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
    }
}

After calling loadPositions:data, _positions is still nil. Pretty straightforward; I have a feeling this has something to do with memory management, but at this point I just need a second set of eyes. What am I missing?


The TT_RELEASE_SAFELY macro sends a release message to its argument before assigning it to nil (IIRC). Why is it any surprise that _positions is nil?

While you may need to release _postitions for whatever reason, you must allocate and initialize a new object and assign its reference to _positions before you can add items to it.

edit: as Luke indicated in his comment, TT_RELEASE_SAFELY is from the three20 library.

#define TT_RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜