Xcode核心数据显示UILabel中的所有实体

时间:2014-05-19 13:16:54

标签: ios uilabel

我想要从标签中的核心数据列出我的所有“来宾”。我使用下面的代码,但我只是在我的UILabel中得到“Guest:(null)。为什么?

AppDelegate *appDelegate = 
                    (AppDelegate*)[[UIApplication sharedApplication] delegate];

NSFetchRequest *request = [[NSFetchRequest alloc]init];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Guests"
                      inManagedObjectContext:appDelegate.managedObjectContext];
[request setEntity:entity];

NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:request error:&error];
NSString *Guests;
NSString *stringText;
stringText = [NSString stringWithFormat:@"%@\n", stringText, 
                [NSString   stringWithFormat:@"Guest : %@" , Guests]];
self.ListAllLabel.text = [NSString stringWithFormat:@"Guest : %@\n"];
[_ListAllLabel setNumberOfLines:0];
[_ListAllLabel sizeToFit];

 for(NSManagedObject *obj in fetchedObjects)
 {
    {         
       NSLog(@"Name:%@\n Last Name %@\n", [obj valueForKey:@"name"],
                                          [obj valueForKey:@"lastname"]);
   }
 }

2 个答案:

答案 0 :(得分:1)

对于初学者来说,这一行是一个问题:

self.ListAllLabel.text = [NSString stringWithFormat:@"Guest : %@\n"];

您在格式字符串中缺少要填写%@的值。

答案 1 :(得分:0)

使用格式说明符(例如%@)打印对象只会调用对象的内置方法说明。 例如[客人描述]; 每个NSObject都实现了这个方法。您不应该使用它来显示标签,因为它有时会导致垃圾值。

要解决您的问题,只需使用简单的字符串连接。

在你的FOR循环中

,你在NSLog中试试这个

     NSString*guestString =@"";
        for(NSManagedObject *obj in fetchedObjects)

        {

            guestString =[guestString stringByAppendingString:[NSString stringWithFormat:@"%@ - Name %@ -Last Name \n",[obj valueForKey:@"name"],[obj valueForKey:@"lastname"]]]
        }
self.ListAllLabel.text = guestString
相关问题