Accessing views from within NSTextField Category?
-
25-09-2019 - |
Question
I've got several different classes in my code utilising identical methods -- resulting in a lot of duplicated lines -- and I recently found out about adding Categories which promises an effective solution to the problem. To give one of the smaller examples, my previous methods were (typically) called in the traditional way like this:
if((thisNum=[self valueInTextField:ctr]) != 0)
//... do stuff here...
- (int)valueInTextField:(int)tagNum
{
NSTextField *field = [[prizeWindow contentView] viewWithTag:tagNum];
int value = [field intValue];
return value;
}
I deleted the above method and added the Category:
@implementation NSTextField(GetFieldValue)
- (int)valueInTextField
{
NSTextField *field = [[[self window] contentView] viewWithTag:tagNum]; // DOESN'T LIKE THIS!!
return [self intValue];
}
@end
However, it doesn't like me asking it to go find the textField itself using [[self window] contentView], so the only way I can get it to work is to (obviously) delete the offending line and pass something like:
if([[[[self window]contentView]viewWithTag:ctr] valueInTextField] != 0)
I'm sure you can see what I'm trying to achieve here. Is there any way I can get a Category to identify the required field as hinted at above -- i.e. without physically passing it myself? Thanks in advance :-)
Solution
If you find yourself needing that method for a lot of windows or window controllers, the right place to put your category would be on one of those classes. For example:
@implementation NSWindow(GetFieldValue)
- (int)valueInTextFieldWithTag:(int)tag
{
NSTextField *field = [[self contentView] viewWithTag:tag];
return [field intValue];
}
@end
OTHER TIPS
However, it doesn't like me asking it to go find the textField itself using [[self window] contentView]
You added a - (int)valueInTextField
method to every NSTextField
via category.
As valueInTextField
is an instance method, you already need a textfield object to call it.
It doesn't make any sense to search for a textfield within the textfield itself. (chicken and egg dilemma)
- (int)valueInTextField
{
NSTextField *field = [[[self window] contentView] viewWithTag:tagNum]; // DOESN'T LIKE THIS!!
return [self intValue];
}
As explained above, searching for the textfield here will not work as you are already in the textfield.
Apart from that you are not using the field variable here anyway.
How many textfields do you have?
Probably it would be easier to manage your textfields with ivars and outlets instead of searching them by tag.