Wednesday, December 31, 2014

Objective C - Few tips for good programming


- Declare Public Properties for exposed data 
Use @property keyword that expose an objects value to outside. By default property is public and readwrite, use readonly if required 
- Use Meaningful name for the properties. For e.g. requestInProgress BOOL flag may have accessor method as @property (readonly,getter=isRequestInProgress) BOOL requestInProgress;
- By Default property is having strong reference. So, declare them to be weak for it be weakly referred. 
- For local variables, use __weak or __strong to make the variable weak or strong 
- When a weak instance variable is assigned to a local variable, the local variable since by default is strong, it will be safe to do the operation until the scope of the local variable finished
For e.g. 
- (void) someMethod 
{
NSObject *cachedObject = self.weakProperty;
[cachedObject doSomething];
}

- Use unsafe_unretained for those classes which doesn’t support weak yet. There are few classes such as NSFont, NSTextView 
- If we have a readonly property, in the header file and want to assign values to it inside the .m file, then either use _propertyName to access it or in the .m file, override the property as readwrite like below 
in .h file 

/**
 * @brief TRUE if the notification detail is already cached. FALSE otherwise.
 */
@property (nonatomic,readonly, getter=isNotificationDetailsCached) BOOL notificationDetailsCached;

In the .m file, either of the below 
@property (nonatomic) BOOL notificationDetailsCached;
self.notificationDetailsCached = TRUE;


references:

No comments:

Post a Comment