make a unique attribute
I'm having a problem to make unique attributes !
I am already searched here for methods that you guys makes an attribute unique in XCode programming:
1: using if(![ARRAY containsObject:object]) ...
2: fetch Array with object and then if ([object count]>0) ...
My situation :
I have an Entity called userAccounts that is contains 2 attribute : userName & passWord .
I have an ArrayController that is bind to managedObjectContext and set to the Entity userAccounts
I have 2 textfield called userNameTF and passwordTF and all I want is to find if the userNameTF string value is added before to the UserAcco开发者_如何学运维unts or not ( uniqueness propose ).
the problem is :
1. NSArrayController does not support containsObject method 2. I can't load userName attributes to an Array to use it for containsObject methodwhat should I do to solve this problem?
Many thanks in Advance
You can get an array containing the value of the userName
property in all of the objects in the array controller using arrangedObjects
and valueForKey:
:
NSArray *userNames = [[arrayController arrangedObjects] valueForKey:@"userName"];
if([userNames containsObject:@"theNewUsername"]) {
// user name taken
} else {
// user name available
}
You could also use indexOfObjectPassingTest:
if you want to find the object which already has the username:
NSArray *objects = [arrayController arrangedObjects];
NSUInteger index = [objects indexOfObjectPassingTest:^(id object, NSUInteger index, BOOL *stop) {
if([[object valueForKey:@"userName"] isEqualToString:@"theNewUsername"]) {
*stop = YES;
return YES;
}
return NO;
}];
if(index == NSNotFound) {
// user name available
} else {
// user name taken by the object at "index" within "objects"
}
精彩评论