OBJ C filling arrays in awakefromnib - scope question?
I'm attempting to fill an array, called from awakeFromNib. My problem is that the variable开发者_如何学C isn't visible when I try to access it.
Here's the relevant snippet:
-(id)returnHaiku
{
return [self getOne:[self getOne:five]] // doesn't know what "five" is...
}
- (void)awakeFromNib
{
[super awakeFromNib];
[self fillArrays];
}
-(id)fillArrays
{
NSArray *five=[NSArray arrayWithObjects: @"blustry zen buddhists",@"barking tiny dogs", @"closeted bigot", @"yowling alley cats",@"shrugging teenagers",@"piece of tangled string", @"ball of woolen yarn", @"big pile of garbage", @"line of well-wishers", @"moldy piece of bread", @"middle manager", @"a terrified rat", @"whispering goofballs", @"various people", @"cross-dressing monkey", @"terrifying dolt", @"sneering idiot", @"grinning sycophant", @"hurtful sloganist",@"annoying haiku",@"hardened criminal",@"vile politician", @"lost generation", @"poetical crap",@"slimy strategist", @"fake conservative", @"old-style liberal",@"evil yuppie scum", @"proud midwesterner",@"artful panhandler",@"noisy spoiled brats",@"frustrated poseurs",nil];
return five;
}
-(id)getOne:(NSArray *)myArray
{
return [[myArray objectAtIndex:arc4random()%myArray.count]stringByAppendingString:@"\n"];
}
I'd appreciate any help you could provide this newbie. Thanks in advance.
Your fillArrays
method is creating a new local NSArray
, and then returning it. However, you're invoking this method like so:
[self fillArrays];
The problem is that you're completely ignoring the return value, which means your array is getting lost in the small void that exists in between stack frames.
five
isn't an instance variable, so it's only visible in fillArrays
. You should make five
an instance variable.
OK.
Answering my own question, but maybe this will help someone else out.
Here's the relevant code, what I ended up with:
-(id)returnHaiku
{
return [self getOne:five];
}
- (void)awakeFromNib
{
[super awakeFromNib];
[self fillArrays];
}
-(void)fillArrays
{
//fill array declared in header file as an instance variable
//Note: it's using arrayWithObjects, a factory method, which I guess
// autoreleases memory after the array is no longer needed...
five=[NSArray arrayWithObjects: @"blustry zen buddhists",@"barking tiny dogs", @"closeted bigot", @"yowling alley cats",@"shrugging teenagers",@"piece of tangled string", nil];
// and here's what I was missing!!
[five retain];
}
-(id)getOne:(NSArray *)myArray
// returns random element from an array
{
return [[myArray objectAtIndex:arc4random()%myArray.count]stringByAppendingString:@"\n"];
}
So my earlier problem apparently involved not retaining the array I was filling. I guess it was being dumped right after being passed out of the method, and so couldn't be used in the later method that picked a random object out of the array.
This works fine.
精彩评论