Archive for 四月, 2011

Cocoa notes (2)

星期四, 四月 28th, 2011

模拟器命令

String format

Cocoa notes (1) 语法

星期一, 四月 25th, 2011

布尔类型
用常量YES/NO表示

Selector 定义

1
SEL sel = @selector(setName:age:); // 类似其他语言里的函数指针

Get object’s class object

1
Class myClass = [myObject class];

判断对象的class

1
2
[myObject isKindOfClass:[UIControl class]] //(含子类)
[myObject isMemberOfClass:[NSString class]] //(不含子类)

数组初始化

1
2
NSArray *array = [NSArray arrayWithObjects:@”Red”, @”Blue”,
@”Green”, nil];

数组indexOf判断

1
if ([array indexOfObject:@”Purple”] == NSNotFound) { ...}

NSDictionary初始化方法

1
2
3
4
NSDictionary *colors = [NSDictionary
dictionaryWithObjectsAndKeys:@”Red”, @”Color 1”,
@”Green”, @”Color 2”, @”Blue”, @”Color 3”, nil];
NSString *firstColor = [colors objectForKey:@”Color 1];

遍历数组

1
2
3
4
5
6
7
8
9
10
11
12
NSArray *array = ... ; // assume an array of People objects
// old school
Person *person;
int count = [array count];
for (i = 0; i < count; i++) {
person = [array objectAtIndex:i];
NSLog([person description]);
}
// new school
for (Person *person in array) {
NSLog([person description]);
}

获得对象的retain数值

1
[object retainCount]

@property和@synthesize的用法
.h文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
// instance variables
NSString *name;
int age;
}
// property declarations
@property int age;
@property (copy) NSString *name;
@property (readonly) BOOL canLegallyVote;
- (void)castBallot;
@end

.m文件中

1
2
3
4
5
6
7
@implementation Person
@synthesize age;
@synthesize name;
- (BOOL)canLegallyVote {
return (age > 17);
}
@end

当property定义的名称和成员变量名不同时

1
2
3
4
5
@interface Person : NSObject {
int numberOfYearsOld;
}
@property int age;
@end
1
2
3
@implementation Person
@synthesize age = numberOfYearsOld;
@end

synthesize允许存在自定义

1
2
3
4
5
6
7
8
@implementation Person
@synthesize age;
@synthesize name;
- (void)setAge:(int)value {
age = value;
// now do something with the new age value...
}
@end

setter方法自定义,但getter方法仍使用synthesize自动的结果

.语法

1
2
3
4
5
6
7
8
9
10
11
@interface Person : NSObject
{
NSString *name;
}
@property (copy) NSString *name;
@end
@implementation Person
- (void)doSomething {
name = @“Fred”; // 直接访问成员变量
self.name = @“Fred”; // 通过setter方法访问
}

自定义类初始化,init方法是覆盖NSObject的

1
2
3
4
5
6
- (id)init
{
if(self=[super init]){
   ...
}
}