我正在尝试填充一个从awakeFromNib调用的数组。我的问题是,当我尝试访问变量时,该变量不可见。
以下是相关摘录:
-(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"];
}
我很感激你能为这个新手提供任何帮助。提前谢谢。
答案 0 :(得分:2)
您的fillArrays
方法正在创建新的本地 NSArray
,然后将其返回。但是,您正在调用此方法:
[self fillArrays];
问题是你完全忽略了返回值,这意味着你的数组在堆栈帧之间存在的小空隙中迷失了。
答案 1 :(得分:1)
five
不是实例变量,因此它仅在fillArrays
中可见。您应该将five
设为实例变量。
答案 2 :(得分:0)
行。
回答我自己的问题,但也许这会帮助其他人。
以下是相关代码,我最终得到的结果:
-(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"];
}
所以我之前的问题显然涉及没有保留我正在填充的数组。我猜它是在被传递出方法之后立即被转储,所以不能在后面的方法中使用从阵列中挑出一个随机对象。
这很好用。