简体   繁体   English

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

[英]Problem in fetching from core data to array

In my core date in the entity name called Event and in that there is an attribute called "name". 在我的核心日期中,名为Event的实体名称包含一个名为“ name”的属性。 I want to fetch all the values of term from coredata to an nsarray. 我想从coredata到nsarray获取term的所有值。 I used the below code and it is not working. 我使用了下面的代码,它不起作用。 Anybody please helpp. 任何人请帮助。

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"];

Your code is close and should have worked even though you were leaking memory. 您的代码很接近,即使您正在泄漏内存,它也应该可以正常工作。

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"];

At this point you should have an array of names which are NSString instances. 此时,您应该具有一个名称数组,它们是NSString实例。

The next question is -- Why? 下一个问题是-为什么? Why do you need to pull them out into an array of strings when you already have the NSManagedObject instances? 当您已经有NSManagedObject实例时,为什么需要将它们拉到字符串数组中? Why disconnect the data from the Core Data objects. 为什么断开数据与核心数据对象的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM