4

I wonder what is considered to be a better practice in a situation when I need to read the contents of the UILabel / UITextField from another view controller between the following two possibilities:

1) Simply create an IBOutlet to the UITextField in the .h file and make it public to everyone
2) Create an NSString readonly property in the .h file, make it readwrite in the implementation file, and update it every time the private UITextField changes.

In my opinion, the second option looks a better approach, because it maintains the OOP encapsulation, but it seems a lot of work to do with every UITextField / UILabel I have in every view controller.

Thoughts? Thanks!

EDIT: In addition, if I need to have the ability to set the IBOutlets from outside, but in a -(void)prepareForSegue: method. So I guess the second option is the only option?

user-123
  • 874
  • 1
  • 13
  • 34

1 Answers1

2

Just create getter methods in the view controller for returning the required data. For example for UITextField :

- (NSString *)getTextFieldText {
   return self.myTextField.text;
}

No need to add a redundant property (NSString *) this way. As with encapsulation you are hiding the private data (i.e your IBOutlets) and expose only the data that is required by others

giorashc
  • 13,691
  • 3
  • 35
  • 71
  • So I have to create a getter method in the header file for every IBOutlet I declare in the implementation file? – user-123 May 26 '14 at 06:52
  • 1
    As with any other data you want an access to. You just don't expose the entire outlet – giorashc May 26 '14 at 07:01
  • And what if in addition I need the ability to set it from outside? Do I have then to create a setter method for every IBOutlet? – user-123 May 26 '14 at 07:01
  • 1
    Well if you need to get and set then maybe your first approach will be the easiest one but any other way you'll to have a getter/setter for each data you want to expose and change outside – giorashc May 26 '14 at 07:03
  • Ok, thanks! BTW, I read somewhere that it is not a good practice to add "get" before a method name. Maybe simply name it -textFieldText? – user-123 May 26 '14 at 07:08
  • Also, I cannot set the IBOutlets in the -prepareForSegue method, so I guess I need to have public properties anyway? – user-123 May 26 '14 at 07:10
  • I put it for clarification as objc method convention is indeed a bit different but do whatever works for you best (unless its really off and confuses your team ;)). – giorashc May 26 '14 at 07:11
  • 1
    @AnatolyAnatoly Correct. If you're using storyboards, the outlets to the UIKit objects won't do anything (because `prepareForSegue:` is called before `awakeFromNib`, which is when the outlets first become available to you.) – Aaron Brager May 26 '14 at 08:08