开发者

How to Implement Primary Key in Core Data for Iphone

I am working on with Core Data. I need to keep a unique value of bandID within Core Data. In my data model i am having

bandImagePath
bandID ---------------primary Key
bandName

Code:

-(IBAction)addToFavButtonPressed:(id)sender
{   
    NSLog(@"add to fav button clicked");    
    SongRequestAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
    NSManagedObjectContext *context = [appDelegate managedObjectContext];   
    NSManagedObject *addToFav;  
    addToFav = [NSEntityDescription insertNewObjectForEntityForName:@"AddToFav" inManagedObjectContext:context];    
    [addToFav setValue:self.imageUrl forKey:@"bandImagePath"];
    NSLog(@"band image path url is %@",self.imageUrl);
    [addToFav setValue:self.bandName forKey:@"bandName"];
    NSLog(@"band name is %@",self.bandName);
    [addToFav setValue:self.bandId forKey:@"bandId"];
    NSLog(@"band ID is %@",self.bandId);
    //NSLog(@"eno is %@",eno.text);

    NSErro开发者_Python百科r *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }       
}


Short answer: you can't, automatically.

Long answer: Core Data does not provide a way to specify an attribute as "unique". There are several reasons why. Rest assured that if this were an easy thing to put in, it would have been put in long ago. So how do you work around it? Basically, you have to first check to see if an AddToFav exists with the specified bandId. If it does, then you don't create a new one. If it doesn't, then you can.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜