从核心数据获取到数组的问题

时间:2010-07-09 05:09:43

标签: iphone objective-c cocoa core-data

在我的核心日期中,名为Event的实体名称中有一个名为“name”的属性。我想从coredata获取term的所有值到nsarray。我使用下面的代码,它不起作用。请任何人帮忙。

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

[request setEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]];

NSError *error = nil;
NSArray *events = [managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, @"Error fetching events: %@\n%@", [error localizedDescription], [error userInfo]);
NSMutableArray *namesArray = [[NSMutableArray alloc]init];
namesArray = [events valueForKey:@"name"];

1 个答案:

答案 0 :(得分:2)

您的代码很接近,即使您泄漏了内存也应该有效。

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

[request setEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]];

NSError *error = nil;
NSArray *events = [managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, @"Error fetching events: %@\n%@", [error localizedDescription], [error userInfo]);
//You were leaking your request here
[request release], request = nil;
//The following line is redundant.  You are leaking an array here
//NSMutableArray *namesArray = [[NSMutableArray alloc]init];
NSArray *namesArray = [events valueForKey:@"name"];

此时,您应该有一个名为NSString个实例的数组。

接下来的问题是 - 为什么?当你已经拥有NSManagedObject个实例时,为什么还需要将它们拉成一个字符串数组?为什么要断开与Core Data对象的数据。