Search code examples
objective-cnsarray

What is difference btw the two


Normally when I want to array of string data separated by commas I do this:

 NSArray *array1 =  [obj1 componentsSeparatedByString:@","];

But some programmer did this:

 NSArray <NSString *>*array1 = [obj1 componentsSeparatedByString:@","];

Both works but I want to know which is better and why.


Solution

  • The latter syntax is a "lightweight generic". This means that when you deal with this collection, it knows you are dealing with a collection of NSString * objects. So it knows that array1[0] must be a NSString.

    By doing this you can get compiler warnings if you accidentally use a method that is not a NSString method. You also enjoy better code completion, showing you only methods and properties for that class. Also, if you were dealing with mutable arrays, the compiler could warn you if you were adding an object of the wrong type.

    Bottom line, lightweight generics are not necessary in Objective-C, but you just take advantage of the compiler's ability to infer types that you anticipate using with your collections. It doesn't enforce any runtime strong typing like you might see in Swift generics (which is why it's called "lightweight"), but it provides more meaningful compile-time warnings and code completion.


    For more information, see