Objective-C:NSMutableArray已初始化并正确添加,但无法检索值

时间:2012-03-20 21:12:36

标签: objective-c ios nsmutablearray

所以我有一个UIScrollingView的子类,它的所有视图都有一个NSMutableArray。我通过传递我要添加到其中的一系列视图来填充此数组。但是,当我在touchesEnded函数中检索这些视图时,我遇到了崩溃。这是违规代码

#import "StageScrollView.h"
#import "Stage.h"


@implementation StageScrollView

@synthesize controller;

-(id)initWithCoder:(NSCoder *)encoder{

    self = [super init];

    if(self != nil)
    {
        stages = [[NSMutableArray alloc] init];
    }

    return self;

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    if(stages == nil)
    {
        NSLog(@".......");
    }

    int index = (int)[controller getCurrentStage];
    Stage *currentStage = [stages objectAtIndex:index];



    UITouch *touch = [[touches allObjects] objectAtIndex:0];
    CGPoint spawn = [touch locationInView:currentStage];

    Performer *temp = [[Performer alloc] init];
    [temp setFrame:CGRectMake(spawn.x, spawn.y, 25, 25)];

    [currentStage addPerformer:temp];

    NSLog(@"Touch ended!! %i", index);

}

//we probably shouldn't init stages here...best practices????
-(void)addStage:(Stage *)stageToAdd
{

    //[stageToAdd retain];

    [stages addObject:[stageToAdd retain]];
    [self addSubview:stageToAdd];

    Stage *temp = [stages objectAtIndex:0];
    NSLog(@"%@", temp);
}


@end

请注意,我已经在initWithCoder中初始化了NSMutableArray,因为我正在从笔尖加载。是的,当我在addStage函数中打印第0个元素时,它会正确打印。但是当我尝试检索touchesEnded函数中的第0个元素时,没有骰子。对于它的价值,当我尝试检查调试器中的阶段时,它会尝试将其读作NSCFString。视图控制器controller通过IB设置。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

由于这是从笔尖加载的,你可以尝试:

-(void)awakeFromNib {
    stages = [[NSMutableArray alloc] init];
}

如果这是UIViewController的子类,还有选项:

-(void)viewDidLoad {
    stages = [[NSMutableArray alloc] init];
}

-(void)viewDidUnload {
    [stages release];
    stages = nil;
}