Reputation: 274
I want an nsstring object that can only store specified lenght of character in it.
If it exceeds it should get truncated from left. For example if i set lenght to 5, and I enter value as Ileana then it should store leana.
I tried by making a category on nsstring but i am out of ideas :
-(void)setMaximumLength:(NSInteger)length;{
if ([self length]>length) {
NSLog(@"exxed");
}
}
Please suggest what should I do? I hve one thng in my mind I need to observe the string size but how to do in a category, and which notification will be called?
Upvotes: 0
Views: 851
Reputation: 2131
The mechanism of truncation can be implemented like this:(for a NSString property of a custom class)
-(void)setName:(NSString*)newName
{
if([newName length]> maxLength)
{
newName = [newName substringWithRange:NSMakeRange([newName length] - maxLength, maxLength];
}
_name = newName;
}
Upvotes: 2
Reputation: 237060
This sounds suspiciously like formatting for display or processing user input or something like that rather than an actual constraint you want to impose on strings in general. In that case, an NSFormatter class or a bit of code in some specific controller property setter would be a good idea.
But if you really want this to be on the string itself, you either need to provide a method like stringByTruncatingToLength:
on NSString or you need to switch to using NSMutableString everywhere, because NSStrings cannot be modified at all and thus a setMaximumLength:
method would be kind of meaningless.
Upvotes: 4