开发者

Core Data Relationships Help ... should be basic i hope

So i have two relationships between two entities in core data, titled "number" and "info." I give the user their number and when i do that i would like for them in return to give me their name so that I can tie it to their specific number. I cannot seem to get the code right to do this. So far the closest that i think i have gotten is this:

        for (UserNumber *pinNumbers in [entryView pinNumberArray]) {
            if ([numberString isEqualToString:pinNumbers.PIN]) {
                UserInfo *info = pinNumbers.info; 开发者_运维问答  
                [info setName:nameField.text];  
            }
        }

where i loop through the number that they have entered and if i can find it inside the array that core data populates i would then like them to assign their name to this. Could anyone show me an example of how this might be done?

Thanks.


If your model is something like this:

Core Data Relationships Help ... should be basic i hope

such that there is a one-to-one bidirectional relationship between UserNumber and UserInfo, then it seems that you could probably have 'number' be an attribute of UserInfo and simplify your model. (Is it the case that 'number' is unique for each UserInfo?)

But, going with your current model, assuming one-to-one relationship, something like this should work - provided that UserNumber has a 'number' attribute and to-one relationship called 'info' that points to a UserInfo.

// Search for UserNumber that has NSString* pinCode as value for attribute PIN
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"UserNumber"
                         inManagedObjectContext:managedObjectContext]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"PIN contains[cd] %@", pinCode];
[fetchRequest setPredicate:predicate];

NSError *error = nil;
NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];

// UserNumber with matching PIN was found, so set name of associated UserInfo.
if ( [items count] == 1 )
    {   
    UserNumber *userNumber = [items lastObject];
    UserInfo *userInfo = [userNumber info];
    [userInfo setName:nameField.text];
    }

Note that items should have either zero or one element. If one, then that first element is the matching UserNumber. By traversing that UserNumber's 'info' relationship, you will be able to get corresponding UserInfo - provided that you've properly created the link previously.

Update

In writing this code snippet, I realized that I don't actually understand what you are trying to do ;-). Is this part of a registration process? If so, then you would need to deal with creation of UserInfo object and relationship between objects. Or is this part of logging in? Or part of editing user info? Anyway, hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜