Learn Objective C(3)Programming with Objective-C - Defining Classes, Working wit

Learn Objective C(3)Programming with Objective-C - Defining Classes, Working with Objects

About Objetive-C
Objects package data with related behavior.

We will not build our own app from scratch, instead we have a large library of existing objects available for our use, provided by Cocoa(for OS X) and Cocoa Touch(for iOS).

1. Defining Classes
1.1 Classes Are Blueprints for Objects
NSString, NSNumber

Mutability Determines Whether a Represented Value Can Be Changed
NSString ---> NSMutableString

Classes Inherit from Other Classes
NSMutableString is inherited from NSString

The Root Class Provides Base Functionality
At least, we inherit from NSObject.

NSObject --> UIResponder -->UIView --> UIControl --> UIButton

1.2. The Interface for a Class Defines Expected Interacctions
Basic Syntax
@interface SimpleClass : NSObject
…snip...
@end

All the public properties and behavior are defined inside the @interface declaration.

Properties Control Access to an Object's Values
@interface Person:NSObject

@property NSString *firstName;
@property NSString *lastName;
@property NSNumber *yearOfBirth;n    // One alternative would be @property int yearOfBirth;

@end

Put an asterisk in front of Objective-C objects to indicate that they are C pointers. And put a semi-colon at the end.

Property Attributes Indicate Data Accessibility and Storage Considerations
Make something read only.
…snip…
@property (readonly) NSString *firstName;
@property (readonly) NSString *lastName;    //Property attributes are specified inside parentheses
…snip…

Method Declarations Indicate the Messages an Object Can Receive
Method on that object --- sending a message to another object by calling a method on that object
- (void) someMethod;

The minus sign(-) indicates that it is an instance method. It is different from class methods.

Methods Can Take Parameters
colons are used in the parameters.
-(void) someMethodWithValue:(SomeType)value;
-(void) someMethodWithFirstValue:(SomeType)value1 secondValue:(AnotherType)value2;

Class Names Must Be Unique
@interface ZJUPerson:NSObject
…snip…
@end

Two-letter prefixes like NS and UI(for User Interface elements on iOS) are reserved for use by Apple.

1.3. The Implementation of a Class Provides Its Internal Behavior
Basic Syntax
#iimport "ZJUPerson.h"
@implementation ZJUPerson
..snip..
@end

Implementing Methods
@interface ZJUPerson:NSObject
-(void)saySomething;
@end

#import "ZJUPerson.h"
@implementation ZJUPerson
-(void)saySomething{
     NSLog(@"something");
}
@end

Method names should begin with a lowercase letter. We suggest use camel case.

1.4. Objective-C Classes Are also Objects
…snip...

2. Working with Objects
2.1 Objects Send and Receive Messages
square brackets [someObject doSomething];

Use Pointers to Keep Track of Objects
Objective-C use variables to keep track of values.

When a local scalar variable (int or float) goes away when the execution reaches the closing brace of the method, the value disappears too.
-(void) myMethod{
     int someInteger = 42;
}

An object's memory is allocated and deallocated dynamically. A local variable is allocated on the stack, while objects are allocated on the heap.
This requires you to use C pointers (which hold memory addresses) to keep track of their location in memory.

-(void) myMethod {
     NSString *myString = @"asdfsadf"
     ..snip..
}
Although the scope of the pointer variable myString is limited to the scope of myMethod, the actual string object that it points to in memory may have a longer life outside that scope.

You Can Pass Objects for Method Parameters
- (void) saySomething:(NSString *) greeting {
     NSLog(@"%@", greeting);
}

Methods Can Return Values
- (int) magicNumber {
     return 42;
}

tracking the return value
int interestingNumber = [someObject magicNumber];

The same thing for Object.
- (NSString *) uppercaseString;

NSString *testString = @"Hello, world!";
NSString *revisedString = [testString uppercaseString];

Automatic Reference Counting(ARC) feature of the Objective-C compiler takes care of these considerations for memory management.

Objects Can Send Messages to Themselves
@implementation ZJUPerson
-(void) sayHello{
     [self saySomething:@"Hello,world"];
}
-(void) saySomething:(NSString *)greeting{
     NSLog(@"%@", greeting);
}
@end

self is also a pointer which points to itself.

Objects Can Call Methods Implemented by Their Superclasses
super -- self

2.2 Objects Are Created Dynamically
The NSObject root class provides a class method, alloc
+ (id) alloc; 

Keyword id means 'some kind of object' in Objective-C. It is a pointer to an object, like (NSObject *)
+ (id) alloc; //make sure we have enough memory
- (id) init;   //make sure we have the right initial values

NSObject *newObject = [[NSObject alloc] init];

Initializer Methods Can Take Arguments
- (id)initWithInt:(int)value;
NSNumber *magicNumber = [[NSNumber alloc] initWithInt:42];

Class Factory Methods Are an Alternative to Allocation and Initialization
+ (NSNumber *) numberWithInt:(int)value;

NSNumber *magicNumber = [NSNumber numberWithInt:42];

Use new to Create an Object If No Arguments Are Needed for Initialization
It is effectively the same as calling alloc and init with no arguments.
ZJUObject *object = [ZJUObject new];

or alternative
ZJUObject *object = [[ZJUObject alloc ] init ];

Literals Offer a Concise Object-Creation Syntax
NSString *something = @"asdfasdf";

NSNumber *myBool = @YES;
NSNumber *myFloat = @3.14f;
NSNumber *myInt = @42;
NSNumber *myLong = @42L;

2.3 Objective-C Is a Dynamic Language
Determining Equality of Objects

if( someInteger == 42) …

When dealing with objects, the == operator is used to test whether two separate pointers are pointing to the same object.
So if we want to test whether two objects represent the same data, we need to call a method like isEqual: available from NSObject.

if ([firstPerson isEqual: secondPerson ]) 

Working with nil
BOOL success = NO;
int magicNumber = 42;

ZJUPerson *somePerson; // automatically set to nil.

Check nil, for instance
if(somePerson != nil) or if(somePerson)


References:
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html


猜你喜欢

转载自sillycat.iteye.com/blog/1960174