目录:
Classes
Methods
Operators
Properties
Constants
NSString
NSArray
NSDictionary
Enumerated Typed
Flow Control Statements
Delegates
Blocks
类
类标头
- @interface Human : NSObject
- // Define properties and methds
- @end
类实现
- #import "Human.h"
- @interface Human ()
- // Define private properties and methods
- @end
- @implementation Human {
- // Define private instance variables
- }
- // Provide method implementation code
- @end
创建一个实例
- Human * anObject = [[Human alloc] init];
方法
定义方法
- // Returns nothing and has no arguments
- - (void)foo;
- //Returns an NSString object and takes one argument of type NSObject
- - (NSString *)fooWithArgument:(NSObject *)bar;
- //Takes two arguments one of type NSObject and a second one of type NSString
- - (void)fooWithArgument:(NSObject *)bar andArgument:(NSString *)baz;
- // Defines a class method (note the + sign)
- + (void)aClassMethod;
实现方法
- - (NSString *)fooWithArgument:(NSObject *)bar{
- //Do something here
- return retValue;
- }
调用方法
- [anObject someMethod];
- [anObject someMethodWithArg1:arg1 andArg2:arg2];
运算符
算术运算符
比较运算符
逻辑运算符
复合赋值运算符
位运算符
其他运算符
属性
定义属性
- @property (attribute1, attribute2) NSString *aProperty;
访问属性
- [anObject aProperty];
- //Alternative
- anObject.aProperty
常量
预处理宏
这并不是一个真正的常量,因为它定义了一个宏在编译之前用真正的值代替所有出现的MAX_NUMBER_OF_ITEMS
- #define MAX_NUMBER_OF_ITEMS 10
使用const
一个更好的方法是使用const
- NSString *const kMyName = @"Clark";
Static和extern
如果你知道只能在实现文件中使用常量,那么你可以用static。使用static意味着这个常量只能在该文件中可用。
- static NSString * const kMyName = @"Clark";
如果你想定义一个全局常量,那么你应该使用extern。
- //.h file
- extern NSString * const kMyName;
- //.m file
- NSString * const kMyName = @"Clark";
NSString
示例:
- NSString *firstName = @"Clark";
- NSString *lastName = @"Kent";
- NSString *fullName = [NSString stringWithFormat: @"My full name is %@ %@", firstName, lastName];
NSString格式限定符
NSArray
示例:
- //Create an array
- NSMutableArray *anArray = [@[@"Clark Kent", @"Lois Lane"] mutableCopy];
- //Add new items
- [anArray addObject:@"Lex Luthor"];
- //Find array length
- NSLog(@"Array has %d items", [anArray count]);
- //Iterate over array items
- for (NSString *person in anArray) {
- NSLog(@"Person: %@", person);
- }
- //Access item with index
- NSString *superman = anArray[0];
- //Remove Object @"Clark Kent"
- [anArray removeObject:@"Clark Kent"];
- //Remove the first Object
- [anArray removeObjectAtIndex:0];
NSDictionary
示例:
- //Create a dictionary
- NSMutableDictionary *person = [@{
- @"firstname" : @"Clark",
- @"lastname" : @"Kent",
- @"age" : [NSNumber numberWithInt:35]
- } mutableCopy];
- //Access values
- NSLog(@"Superman's first name is %@", person[@"firstname"]);
- //or
- NSLog(@"Superman's first name is %@", [person objectForKey:@"firstname"]);
- //Find number of items in dicitonary
- [person count];
- // Add an object to a dictionary
- [person setObject:@"job" forKey:@"teacher"];
- //Remove an object to a dictionary
- [person removeObjectForKey:@"firstname"];
枚举类型
苹果的示例:
每个枚举被赋予一个响应的整数值,所以
- typedef enum {
- UIButtonTypeCustom = 0,
- UIButtonTypeSystem,
- UIButtonTypeDetailDisclosure,
- UIButtonTypeInfoLight,
- UIButtonTypeInfoDark,
- UIButtonTypeContactAdd,
- UIButtonTypeRoundedRect,
- } UIButtonType;
与下述代码一样
- typedef enum {
- UIButtonTypeCustom = 0,
- UIButtonTypeSystem = 1,
- UIButtonTypeDetailDisclosure = 2,
- UIButtonTypeInfoLight = 3,
- UIButtonTypeInfoDark = 4,
- UIButtonTypeContactAdd = 5,
- UIButtonTypeRoundedRect = 6,
- } UIButtonType;
不要求明确地定义第一个枚举的值,并且它默认为0
使用枚举类型
- UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoLight];
或者创建一个变量传递到方法,像这样
- UIButtonType myButtonType = UIButtonTypeCustom;
- UIButton *myButton = [UIButton buttonWithType:myButtonType];
由于它们不是对象,所以你必须打印枚举类型为整数
- UIButtonType myButtonType = UIButtonTypeRoundedRect;
- // Bad, will give you a warning and might even crash
- NSLog(@"%@", myButtonType);
- // Good, will properly print the value as an integer
- NSLog(@"%d", myButtonType);
流程控制语句
If-else语句
- if (someCondition) {
- // Execute if the condition is true
- } else if (someOtherCondition) {
- // Execute if the other condition is true
- } else {
- // Execute if the none of the above conditions are true
- }
三元运算符
- someCondition ? @"True" : @"False";
For循环
- for (int i = 0; i < totalCount; i++) {
- // Do something here
- }
While循环
- while (someCondition) {
- // Do something here
- }
Do While循环
- do {
- // Do something here
- } while (someCondition);
Switch语句
- switch (aLabel)
- {
- case kLabelA:
- // Execute this if matched
- break;
- case kLabelB:
- // Execute this if matched
- break;
- default:
- // Execute this if matched
- break;
- }
委托
委托是一种设计模式。当一个事件发生时,委托允许一个对象把消息传递给其他对象。请查阅
苹果官方文档。
成为一个框架类的委托:
第一步,声明类采用了类/父类名字后,方括号里类定义中的协议。
- //MyTableViewController.h
- @interface MyTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
- @end
第二步,设置对象作为委托
- //MyTableViewController.m
- [tableView setDelegate:self];
- @end
第三步,实现委托方法
为自定义的类实现委托:
第一步,声明协议方法
- // Superman.h
- #import <Foundation/Foundation.h>
- @protocol SupermanDelegate <NSObject>
- - (void)dodgeBullet;
- - (void)seeThroughThings;
- - (void)fly;
- @optional
- - (void)eat;
- @end
- @interface Superman : NSObject
- // Create a property for the delegate reference
- @property (nonatomic, weak) id <SupermanDelegate> delegate;
- // Define other methods and properties
- @end
第二步,设置委托对象
- // Superman.m
- [self setDelegate:anObject];
第三步,开始发送委托消息
- // Superman.m
- [self.delegate fly];
Blocks
Blocks是添加到C,Objective-C和C++中一个语言级别的特性,它允许你创建不同的代码段,这些代码段就像值一样可以在方法和函数间传递。更多信息请查阅Programming with Objective-C - Working with Blocks
声明block局部变量:
- returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
声明block属性:
- @property (nonatomic, copy) returnType (^blockName)(parameterTypes);
接收block作为一个方法参数:
- - (void)aMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;
在方法调用中将block作为一个参数传递
- [someObject someMethodThatTakesABlock: ^returnType (parameters) {...}];
定义一个block类型:
- typedef returnType (^TypeName)(parameterTypes);
- TypeName blockName = ^returnType(parameters) {...};