简体   繁体   中英

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. 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. 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. And yes, when I print the 0th element in the addStage function, it does print properly. But when I try to retrieve the 0th element in the touchesEnded function, no dice. For what it's worth, when I try to inspect stages in the debugger, it tries to read it as an NSCFString . The view controller controller is set via IB.

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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