Re: Accessing programatically to attribute length in run-time
Re: Accessing programatically to attribute length in run-time
- Subject: Re: Accessing programatically to attribute length in run-time
- From: "Stephen Deken" <email@hidden>
- Date: Wed, 21 Feb 2007 09:38:27 -0600
On 2/21/07, Txinto Vaz <email@hidden> wrote:
Everything works fine except I have found no way to know the length of the
string fields to be created in the database. I think a good idea is to use
the validation argument "max length" of the model to define this length.
... But
the problem is that I don't know how to access to this value (if it is
possible).
Do you mean that you are trying to find the maximum length of the
string as specified in the managed object model? That's a tricky
number to get at, because it's actually stored as an NSPredicate in
the model.
I'm not sure what your goal is with this, and there's almost certainly
a better way to get you to where you want to be, but you'd have to do
something like this (typed in gmail):
NSManagedObjectContext *moc = ...;
NSEntityDescription *ed = [NSEntityDescription entityForName:@"..."
inManagedObjectContext:moc];
NSNumber *maxLength = nil;
NSEnumerator *iter = [[ed properties] objectEnumerator];
id prop = nil;
while ((prop = [iter nextObject]))
{
if (![prop isKindOfClass:@"NSAttributeDescription"])
continue;
// here, prop is an NSAttributeDescription object
if (![[prop name] isEqualToString:@"..."]) // whatever you're looking for
continue;
NSEnumerator *i2 = [[prop validationPredicates] objectEnumerator];
id pred = nil;
while ((pred = [i2 nextObject]))
{
if (![pred isKindOfClass:@"NSComparisonPredicate"])
continue;
// here, pred is an NSComparisonPredicate object
// we're looking for the 'max length' property, which means that the
// comparison operator will be '<=', the left side of the expression
// will be 'length', and the right side will be a constant number.
if ([pred predicateOperatorType] !=
NSLessThanOrEqualToPredicateOperatorType)
continue;
NSExpression *le = [pred leftExpression];
if ([le expressionType] != NSKeyPathExpressionType)
continue;
if (![[le keyPath] isEqualToString:@"length"]) // this might
be self.length instead
continue;
// ok, this seems to be our max length parameter
NSExpression *re = [pred rightExpression];
if ([re expressionType] != NSConstantValueExpressionType)
continue; // non-constant max length?
id tmp = [re constantValue];
maxLength = [tmp isKindOfClass:@"NSString"] ? [tmp intValue] : tmp;
break;
}
if (maxLength != nil)
break;
}
Then if maxLength is non-nil, it should contain the maximum length constraint.
Again, there's probably a better way to do what you're trying to do.
--
Stephen Deken
email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden