简体   繁体   English

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

[英]Objective-C: NSMutableArray initialized and added to properly, but values cannot be retrieved

so I have a subclass of UIScrollingView that's got an NSMutableArray off all it's views. 所以我有一个UIScrollingView的子类,该子类的所有视图都没有NSMutableArray。 I populate this array by passing in the series of views I want to add to it. 我通过传递要添加到其中的一系列视图来填充此数组。 However, when I go to retrieve these views in my touchesEnded function, I get a crash. 但是,当我在touchesEnded函数中检索这些视图时,发生崩溃。 Here is the offending code 这是有问题的代码

#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

note that I've initialized the NSMutableArray in initWithCoder , as I'm loading from a nib. 请注意,当我从笔尖加载时,我已经在initWithCoder初始化了NSMutableArray。 And yes, when I print the 0th element in the addStage function, it does print properly. 是的,当我在addStage函数中打印第0个元素时,它确实可以正确打印。 But when I try to retrieve the 0th element in the touchesEnded function, no dice. 但是,当我尝试在touchesEnded函数中检索第0个元素时,没有骰子。 For what it's worth, when I try to inspect stages in the debugger, it tries to read it as an NSCFString . 值得的是,当我尝试检查调试器中的阶段时,它将尝试将其读取为NSCFString The view controller controller is set via IB. 通过IB设置视图控制器controller

Thanks for any help! 谢谢你的帮助!

Since this is loading from a Nib you could try: 由于这是从笔尖加载的,因此您可以尝试:

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

If this is a subclass of UIViewController there is also the option: 如果这是UIViewController的子类,则还有以下选项:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM