供将要学习objective-c的人士

来源:互联网 发布:福师大网络教育作业 编辑:程序博客网 时间:2024/06/11 00:24

Class Header (.h)

#import"AnyHeaderFile.h"@interfaceClassName :SuperClass

// define public properties// define public methods

@end

Class Implementation (.m)

#import"YourClassName.h"

@interfaceClassName ()
// define private properties// define private methods@end

@implementationClassName {
// define private instance variables}

// implement methods

@end

Defining Methods

- (type)doIt;
- (
type)doItWithA:(type)a;- (type)doItWithA:(type)a

b:(type)b;Implementing Methods

- (type)doItWithA:(type)ab:(type)b {

// Do something with a and b...

returnretVal;}

Creating an Object

ClassName* myObject =[[ClassNamealloc]init];

Calling a Method

[myObject doIt];
[myObject
doItWithA:a];[myObjectdoItWithA:ab:b];

Declaring Variables

typemyVariable;

Variable types

int

1, 2, 500, 10000

floatdouble

1.5, 3.14, 578.234

BOOL

YESNO

ClassName *

NSString *, NSArray *, etc.

id

Can hold reference to any object



Defining Properties

@property (attribute1, attribute2)type propertyName;

strong

Adds reference to keep object alive

weak

Object can disappear, become nil

assign

Normal assign, no reference

copy

Make copy on assign

nonatomic

Make not threadsafe, increase perf

readwrite

Create getter&setter (default)

readonly

Create just getter

Using Properties

[myObject setPropertyName:a];myObject.propertyName = a; // alt

a = [myObject propertyName];
a = myObject.
propertyName// alt 


What is a Property?

1) Automatically defines a private instance variable:

type_propertyName;
2) Automatically creates a getter and setter:

- (type)propertyName;
- (
void)setPropertyName:(type)name;

Using _propertyNameuses the private instancevariable directly. Usingself.propertyNameusesthe getter/setter.

Custom Initializer Example

- (id)initWithParam:(type)param {if((self= [superinit])) {

_propertyName = param;}

                 return self;             }

NSString Quick Examples

NSString*personOne =@"Ray";NSString*personTwo =@"Shawn";NSString*combinedString =

[NSStringstringWithFormat:@"%@: Hello, %@!",personOne, personTwo];

NSLog(@"%@", combinedString);
NSString*tipString =@"24.99";
floattipFloat = [tipStringfloatValue];

NSArray Quick Examples

NSMutableArray*array =
[
@[person1, person2]mutableCopy];

[array addObject:@"Waldo"];NSLog(@"%d items!", [arraycount]);for(NSString*person inarray) {

NSLog(@"Person: %@", person);}

NSString*waldo = array[2];


0 0
原创粉丝点击