开发者

Advantage of data type id vs NSString in Objective C?

开发者 https://www.devze.com 2022-12-08 17:38 出处:网络
This开发者_Python百科 code... NSString * s = [[NSString alloc] initWithString:@\"Hello, World\"];

This开发者_Python百科 code...

NSString * s = [[NSString alloc] initWithString:@"Hello, World"]; 
s = s.lowercaseString;
NSLog(@"%@", s);

...allows the use of dot notation but is strongly typed. This code...

id s = [[NSString alloc] initWithString:@"Hello, World"]; 
s = [s lowercaseString];
NSLog(@"%@", s);

... is weakly typed and requires use of square brackets.

Other than that, is there any advantage of using one over the other?


If you're creating an NSString, then you might as well declare it as an NSString, and let the compiler help you.

The point of using id is to prevent strong coupling, and to use objects whose types are not known until a later time. e.g IBAction methods include the sender as a parameter as an id, because the exact type of the object isn't known.

Edited to add:

You may be new to the language, so I'll mention a couple of things

Firstly, where you have @"Hello, World", you already have an NSString, just one that is static. So you don't need to go through initWithString to create it. Just write:

NSString *s = @"Hello, World";

And, because you didn't alloc it, you don't have to worry about releasing it.

Secondly s.lowerCaseString. As Stephen has already answered, this is considered to be bad style. When you change a string to lower case, you aren't getting a property of the the string, you are causing an operation to be done on the string, in which case, you really should use bracket syntax.


Yes. The compiler warns you if you try to put a NSString into a method that expects a NSNumber.

It's more likely that the compiler finds your mistakes.


Arguably the former code is incorrect. You should only really use the dot notation to get/set properties, and lowercaseString is a method.

Otherwise, as you suggest, the only real difference is type safety. If you had a typo, say you put [a loercaseString], the compiler wouldn't shout at you.

There are certainly cases where you'd use id but your example is not one of them

0

精彩评论

暂无评论...
验证码 换一张
取 消