Friday, December 23, 2011

What is with - and + before methods?

When defining a class, methods are defined prefixed with "-" or "+". What is it with the signs?

- indicates the method is an instance method (per class instance)
+ indicates the method is a class method (one for all instances, equivalent to static in java/flex)

Example:
- (void) instanceMethod
+ (int) getCounter

No packages

There are no packages in objc unlike java/flex. All classes in objc are scoped as public equivalent in java/flex. To uniquely differentiate class names, developers should follow a thumb rule (ugly but worth it) when creating framework classes used by other developers:
Prefix the class name with keyword that uniquely describes your classes framework

An example is a classes that start with unique keyword "NS" for classes in cocoa framework - NSObject, NSString, NSRange etc.

Though the classes used only specific to your code and not to be used by other developers need not have this prefix, I personally would recommend it for you to easily recognize the class in a pile as it gets big.

Scope of class instance variables

The class instance variables can be scoped in objc similar to java/flex. @private will allow methods of the class only to access the instance variables. @protected (or no access specifier mentioned, default) will allow methods in the current class and methods of subclass to allow access to instance variable. @public is the equivalent of public in java/flex.

Scope of Class and methods

scope of class and methods in objc cannot be controlled. In other words, they are scoped same as public in java.