この記事は何についてですか?
2つの事実。 世界には多くのJavaプログラマーがいます。 Objective-Cの人気は高まっています。 結論:Objective-Cを学習するJavaプログラマーは珍しくありません。 言語間の主な違いを知っている場合、Javaの既存の知識を効果的に使用して、Objective-Cの記述をすぐに開始できます。
私はCで始め、過去15年間Javaで書いて、時にはC ++、Python、Perlに切り替え、Scalaを興味を持って見ていました。 そして今、Objective-C。
各旅行から、通常、「私たち」と「彼ら」の最も面白い違いに関するいくつかの物語があります。 完全なふりをすることなく、Objective-Cの機能について説明します。これは、Javaからの異星人として私を特に驚かせました。 後で、これらの機能を理解または拒否すると、Objective-C構文で記述されたJavaコードが生成されることに気付きましたが、Objective-Cコードだけを記述する方がはるかに自然です。 言語は構文だけでなく、主にイディオムです。 繰り返しますが、これはガイドではなく、旅行者のメモです。 興味深いと思われる場合は、今後の記事で観察結果について引き続き説明します。
メソッドではなくメッセージを送信します
Java:
object.method(param);
Objective-C:
[object method:param];
Java , Objective-C — . . -, , ( , , , Java ), (
selector), -. , , .
, Java , (
warning). — . — .
?
Java:
public Feature addFeature (String name, String value, boolean isOptional);
Objective-C:
-(Feature*) addFeature :(NSString*)name withValue:(NSString*)value asOptional:(BOOL) optional:
Objective-C “” . , ,
addFeature:withValue:asOptional:SEL selector = @selector(addFeature:withValue:asOptional:);
, , , 16 . 16 .
: ,
Java
Objective-C:
@interface NSString (LetsAugment)
-(BOOL) isGoodActor;
@end
,
NSObject. (
category).
LetsAugment,
isGoodActor NSString.
NO (false Java), ,
YES (true) , . — :
if ([@”Steven Seagal” isGoodActor]) NSLog (@”Yeah!”) else NSLog (@”What's wrong with you?”);
, , .
, -, . , , . . -, .
:
Java:
MyTao tao = null;
int howManyHands = tao.clap();
Objective-C:
MyTao* tao = nil;
int howManyHands = [tao clap];
, ,
NullPointerException , , . —
howManyHands 0. 1, , .
.
nil (null Java), (nil, 0, NO ..). , .
Java: ()
class Profile {
int getVersion() {
...
}
class Feature {
Profile getProfile(String name) {
...
}
class Phone {
Feature getFeature(String name) {
...
}
class PhoneFactory {
static Phone designAndProduce(String model) {
...
}
}
...
int version = 0;
Phone phone = PhoneFactory.designAndProduce(“iphone5”);
Feature btFeature = phone.getFeature(“bt”);
if (btFeature != null) {
Profile profile = btFeature.getProfile(“a2dp”);
if (profile != null) {
version = profile.getVersion();
}
}
Objective-C:
@interface Profile : NSObject
@property (readonly) int version;
@end
@interface Feature : NSObject
- (Profile*) getProfile:(NSString*)name;
@end
@interface Phone : NSObject
+ (Phone*) designAndProduce:(NSString*)name;
-(Feature*) getFeature:(NSString*)name;
@end
...
Phone* phone = [Phone designAndProduce:@"iphone5"];
Feature* btFeature = [phone getFeature:@"bt"];
Profile* profile = [btFeature getProfile:@"a2dp"];
int version = profile.version;
Objective-C Java .
[phone getFeature:@«bt»] nil, version 0.
« »? nil , , , . (getter/setter). , Objective-C (-
profile.version?) — (
property), .