Search code examples
iosobjective-ccocoa-touchnotificationsretain

retain data member and Notifications


Just need 2 really basic clarifications.

1.

Lets say I have a class A which has a member declared like:

@property (nonatomic,retain) NSString* stringInstanceVariable;

In one of my methods, I want to initialize stringInstanceVariable to be some string. Do I need to retain it or not?

should I call:

stringInstanceVariable = [[NSString stringWithCString:"Hello"] retain];

Or

stringInstanceVariable = [NSString stringWithCString:"Hello"];

Or maybe I should call:

self.stringInstanceVariable = [NSString stringWithCString:"Hello"];

2.

Using interface builder , when I right click a textfield control for example, I get a list of methods. what are those exactly? Notification that I can register to observe? And I know I can implement and then connect them using IB, I just want to know if and how for example I can do this without IB using just code. Maybe I can do it by using "addTarget:action:forControlEvent".

But if that's the case then what is the difference between events and notifications in Cocoa? or comparing to delegation is more appropriate.


Solution

  • To answer your second question, there is the UITextFieldDelegate protocol that specifies a "contract" of sorts, of methods that the delegate agrees to implement (unless they are designated as optional).

    In Interface Builder, you wire up your view controller as the text field's delegate. Making your view controller the delegate means that you agree to set up non-optional methods in view controller that get called when things happen in or to the text field.

    For example, the delegate's -textFieldDidBeginEditing method gets called when the user starts editing text in the text field. You would put code here if it is useful to you, to track when the field's text content may be changed. There are other delegate methods you can (optionally) implement.

    The delegate pattern is ubiquitous in iOS development. Table views are another good example. You set up a controller class as a delegate for a UITableView instance. The controller contains several non-optional delegate methods that specify how many rows and sections the table view has, as well as the cell content.

    Notifications are different from delegates, in that usually only one instance of an object is set up to be the delegate of another object. Notifications are useful when you want several objects to be able to listen for something happening in another object. A notification center broadcasts notifications to whichever objects are registered to listen for them. The registered objects then agree to run a method ("selector" in Objective-C speak) when the notification is received.