我有一个核心数据模型,它有一个名为Goodie的实体,属性为thingsYouWant,类型为String。
当你按下一个按钮时,我想从“thingsYouWant”中随机选择一个单词,并将其放入一个带格式的字符串中。
但我一直在获取一个NSString,它可能不会响应objectAtIndex错误-(
更新:
这是我的工作代码:
-( void ) viewDidLoad {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription
entityForName:@"Goodie" inManagedObjectContext:
self.managedObjectContext ]];
NSError *error = nil;
NSArray *array = [self.managedObjectContext
executeFetchRequest:request error:&error];
if (array == nil)
{
// Deal with error...
}
if(array.count > 0){
int r = random()% [array count];
goodie = [array objectAtIndex:r];
} else { // no one to fetch - generate one
goodie = [NSEntityDescription
insertNewObjectForEntityForName:@"Goodie"
inManagedObjectContext:self.managedObjectContext ];
}
- (void) winText {
NSArray *components = [[goodie thingsYouWant]
componentsSeparatedByString:@" "];
NSInteger randomIndex = (random() % [components count]);
NSString *newWord = [components objectAtIndex:randomIndex];
winLabel.text =[NSString stringWithFormat: @"Congratulations,
the carrot you have earned is -->>> %@", newWord];
}
谢谢:-D
斯科夫