【问题标题】:How Can I Get A Random String out of Core Data?如何从核心数据中获取随机字符串?
【发布时间】:2012-01-22 22:57:16
【问题描述】:

我有一个获取请求,它使用 NSPredicate 从核心数据中捕获一组 NSString 记录。但是,输出似乎难以理解。我看不到我错过了什么。代码如下:

NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entityQuote = [NSEntityDescription entityForName:@"Quotes" inManagedObjectContext:context];
NSFetchRequest *fetchRequestQuote = [[NSFetchRequest alloc] init];
[fetchRequestQuote setEntity:entityQuote];  

if ([sourceString isEqualToString:@"one"]) sourceString = @"  one";
if ([sourceString isEqualToString:@"two"]) sourceString = @"  two";
if ([sourceString isEqualToString:@"three"]) sourceString = @"  three";
if ([sourceString isEqualToString:@"four"]) sourceString = @"  four";
if ([sourceString isEqualToString:@"five"]) sourceString = @"  five";

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"quote contains %@", sourceString];
[fetchRequestQuote setPredicate:predicate];
NSArray *chosenSourceAll = [context executeFetchRequest:fetchRequestQuote error:nil];
int countSource = [chosenSourceAll count];
int rNumber = arc4random() % countSource;
NSLog(@"%d, %d, %@", rNumber, countSource, [chosenSourceAll objectAtIndex:rNumber]);

我在控制台的输出是:

2, 38, <NSManagedObject: 0x8c65860> (entity: Quotes; id: 0x7fc4790 <x-coredata://9FC73918-E9DC-4CDB-9D32-E640C9E24C71/Quotes/p3> ; data: <fault>)

关于如何让字符串内容输出的任何想法?我是否不恰当地格式化了我的获取请求?我确实检查了 sqlite3 文件,字符串很好。

【问题讨论】:

    标签: objective-c core-data nspredicate nsfetchrequest


    【解决方案1】:

    看起来您的 Quotes 类根本不是 NSString,而是 NSManagedObject。您可能在 Quotes 对象上定义了一些属性,该对象是您实际存储报价正文的位置。这是您在打印到日志时要访问的属性,而不是对象本身。

    如果这不正确,请发布有关您的 Quotes 课程的更多信息。

    【讨论】:

    • 谢谢吉米!你是对的。我必须在这一行中引用属性“quote”:quoteTextView.text = [[chosenSourceAll objectAtIndex:rNumber] valueForKey:@"quote"];
    猜你喜欢
    • 2018-04-27
    • 1970-01-01
    • 2021-06-15
    • 2018-08-11
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2011-02-18
    相关资源
    最近更新 更多