Objective-C > Basic Syntax
- Objective-C was licensed by NeXT in 1988 and was the basis for its application framework API, NeXTStep.
- Eventually, NeXT and Apple merged, and the NeXT application framework evolved into Cocoa, the framework for Mac OS X applications, still revolving around Objective-C.
- It also explains why Cocoa class names often begin with “NS” — it stands for “NeXTStep.”
- if a variable is an instance of the class MyClass, that variable is of type MyClass* — a pointer to a MyClass.
- MyClass* is the meaning of "a MyClass instance".
- s is an NSString* to access the "real" NSString. Once the variable s is declared as a pointer to an NSString, the uppercaseString message is sent directly to the variable s.
- NSString* s = @"Hello, world!";
- NSString* s2 = [s uppercaseString];
- NSLog(@"%@, s2);
- NSString* is a pointer to an NSString.
- Merely declaring an instance reference's type doesn't bring any instance into existence. For example:
- NSString* s; //only a declaration; no instance is pointed to
- After that declaration, s is types as a pointer to an NSString, but it is not in fact pointing to an NSString. You have created a pointer, but you haven't supplied an NSString for it to point to.
- You can declare a variable as an instance reference in one line of code and initialize it later, like this:
- NSString* s;
- s = @"Hello, world";
- Same, NSString* s = @"Hello, world";
- If you aren't going to initialize an instance reference pointer at the moment you declare it by assigning it a real value, it's a good idea to assign it nil:
- nil --> this instance reference isn't pointing to any instance.
- To test an instance reference against nil as a way of finding out whether it is in fact pointing to a real instance.
- if (nil == s) // ...
- if (!s) // ...
- , where zero means false in a condition
- Many Cocoa methods use a return value of nil:
- NSString* path = // ... whatever
- NSStringEncoding enc = // ... whatever
- NSError* err = nil;
- NSString* s = [NSString stringWithContentsOfFile:path encoding:enc error: &err];
- if (nil == s) // oops! something went wrong
- In Objective-C, sending a message to nil is legal and does not interrupt execution. Objective-C doesn't constitutes a runtime error when sending a message to nil
- Morever, if you capture the result of the method call, it will be a form of zero - which means that if you assign that result to an instance reference pointer, it too will be nil:
- NSString* s = nil; // now is nil
- NSString* s2 = [s uppercaseString] // now s2 is nil;
-
No comments:
Post a Comment