coredata的问题

时间:2009-12-09 13:29:37

标签: iphone sdk

我有一个问题,每当我使用coredata插入数据时,一切都很顺利。但是在检索时,我总是检索到相同的对象。我在插入方法中插入了具有多个属性(如id,name,address等)的actor的对象,我可以看到插入的所有内容(实际上我正在从xml文件中检索)。我的设置方法如下:=

[poi setActorCity:[NSString stringWithFormat:@"%@",[poi1 objectAtIndex:j]]];

其中,poi是我managedObjectClass POI1 的对象。那是个问题吗? &安培; j index仅用于跟踪poi1数组中的xml值。请帮忙......

  • (无效)的addEvent {

[actorsArray removeAllObjects];

NSEntityDescription * entity1 = [NSEntityDescription entityForName:@“POI1”inManagedObjectContext:self.managedObjectContext];

POI1 * poi =(POI1 *)[NSEntityDescription insertNewObjectForEntityForName:@“POI1”inManagedObjectContext:managedObjectContext];

for(NSInteger i=0;i<[Actors count];i++)
{
    NSMutableArray *poi1=[[NSMutableArray alloc]init];
    poi1=[Actors objectAtIndex:i];
    for(int j=0;j<[poi1 count];j++)
    {
        if(j==1)
        {
            [poi setActorName:[NSString stringWithFormat:@"%@",[poi1 objectAtIndex:j]]];

        } //Like this it inserts for every attribute
            }
    [actorsArray insertObject:poi atIndex:i];       
    [poi release];
}
[self saveAction]; //saving the managedObjectContext

}

这是'我的获取方法......

- (无效)fetchResult {

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

NSEntityDescription * entity1 = [NSEntityDescription entityForName:@“POI1”inManagedObjectContext:self.managedObjectContext];

[fetchRequest setEntity:entity1];

NSArray *items = [self.managedObjectContext
              executeFetchRequest:fetchRequest error:&error];

for(NSInteger k=0;k<[items count];k++)
{
    POI1 *_poi=[[POI1 alloc]init];
        _poi = [items objectAtIndex:k];
         NSString *str=[NSString stringWithFormat:@"%@",[_poi actorName]]; //This' for testing... Shows me same name every time..,
}

[fetchRequest release];     

}

3 个答案:

答案 0 :(得分:0)

有点难以准确回答这些信息,但我有根据的猜测是你不会每次都创建新的poi实例并继续为你的数组添加相同的引用。

答案 1 :(得分:0)

听起来你的提取有问题。检查你的谓词。如果它返回相同的对象,则最可能的原因是您的谓词被编写为只发现一个对象。

Edit01:

这一行是你的问题:

POI1 *poi = (POI1 *)[NSEntityDescription insertNewObjectForEntityForName:@"POI1" inManagedObjectContext:managedObjectContext];

尽管调用的类是'NSEntityDescription',但此方法返回一个托管对象实例。现在,您创建一个POI1实例,然后继续为其分配不同的属性。您看到相同的值,因为您只创建,填充并保存了一个对象。

将对象创建移动到循环中:

for(NSInteger i=0;i<[Actors count];i++)
{
        POI1 *poi = (POI1 *)[NSEntityDescription insertNewObjectForEntityForName:@"POI1" inManagedObjectContext:managedObjectContext];
        NSMutableArray *poi1=[[NSMutableArray alloc]init];
        poi1=[Actors objectAtIndex:i];
        for(int j=0;j<[poi1 count];j++)
        {
                if(j==1)
                {
                        [poi setActorName:[NSString stringWithFormat:@"%@",[poi1 objectAtIndex:j]]];

                } //Like this it inserts for every attribute
                        }
        [actorsArray insertObject:poi atIndex:i];               
        [poi release];
}

这会在每次传递时创建一个新的POI1,以便Actors数组的每个元素都有一个包含其数据的相应POI1个实例。

答案 2 :(得分:0)

确保在执行所有这些插入后(可能在每次插入后)保存managedObjectContext,否则信息将永远不会留下临时内存。