Archive for the '全部' Category

HOW TO – 如何向IPhone模拟器的photos添加图片

星期二, 五月 31st, 2011

默认图片是空的
有提示文字“You can sync photos and videos onto your iPad Simulator using iTunes.”
结果有人发现,其实这是坑爹的文字模板”You can sync photos and videos onto your {DEVICE_NAME} using iTunes.”,{DEVICE_NAME}会被[[UIDevice currentDevice] model]替换,如果是在真机上测试,itunes当然是可以同步图片的,但是模拟器上无法用itunes。

解决办法:
首先打开模拟器,并进入photo
然后用safari浏览到一张图片,然后拖拽图片到iphone模拟器
模拟器会用模拟器的safari打开图片
然后在图片上长按鼠标,弹出对话框,选择保存,这时再回到phot里就可以看到图片了。

Cocoa notes (22) Timer

星期一, 五月 30th, 2011

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Timers/Articles/usingTimers.html#//apple_ref/doc/uid/20000807-CJBJCBDE

Cocoa notes (21) Fast Enumeration

星期五, 五月 27th, 2011

枚举, for … in 语法

1
for ( Type newVariable in expression ) { statements }

1
2
Type existingItem;
for ( existingItem in expression ) { statements }

使用for…in语法的expression必须实现 NSFastEnumeration协议,NSArray, NSDictionary, NSSet, NSDictionary 等 实现了此协议。

例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSArray *array = [NSArray arrayWithObjects:
        @"One", @"Two", @"Three", @"Four", nil];
 
for (NSString *element in array) {
    NSLog(@"element: %@", element);
}
 
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
    @"quattuor", @"four", @"quinque", @"five", @"sex", @"six", nil];
 
NSString *key;
for (key in dictionary) {
    NSLog(@"English: %@, Latin: %@", key, [dictionary objectForKey:key]);
}

也可以使用NSEnumerator对象进行遍历

1
2
3
4
5
6
7
8
9
10
11
12
NSArray *array = [NSArray arrayWithObjects:
        @"One", @"Two", @"Three", @"Four", nil];
 
NSEnumerator *enumerator = [array reverseObjectEnumerator];
for (NSString *element in enumerator) {
    if ([element isEqualToString:@"Three"]) {
        break;
    }
}
 
NSString *next = [enumerator nextObject];
// next = "Two"

Core Data

星期二, 五月 24th, 2011

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html

路径问题
sqlite文件不能作为resource bundle存在在项目中,否则会被每次覆盖
最好存储在Library或Documents

获得Documents路径

1
2
3
4
5
6
- (NSString *)applicationDocumentsDirectory {
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

检查documents路径下是否有db文件,如果没有,从resource bundle路径下copy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    NSString * dbPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"user.db"];
    NSLog(@"dbPath=%@", dbPath);
   
    NSFileManager * fm = [NSFileManager defaultManager];
   
    if(![fm fileExistsAtPath:dbPath])
    {
        NSString * localPath = [[NSBundle mainBundle] pathForResource:@"user" ofType:@"db"];
        if(localPath)
            [fm copyItemAtPath:localPath toPath:dbPath error:nil];
    }
   
    self.window.rootViewController = self.viewController;
    self.viewController.dbPath = dbPath;
    [self.window makeKeyAndVisible];
    return YES;
}

MacOS 启用root用户

星期一, 五月 23rd, 2011

从 Apple 菜单中,选取系统偏好设置…。
从显示菜单中,选取帐户。
点按锁图标并使用管理员帐户进行鉴定。
点按“登录选项…”。
点按右下部的“编辑…”或“加入…”按钮。
点按“打开目录实用工具…”按钮。
点按“目录实用工具”窗口中的锁图标。
输入管理员帐户名称和密码,然后点按“好”。
从编辑菜单中选取启用 Root 用户。
在“密码”和“验证”字段中输入您想要使用的 root 密码,然后点按“好”。

Cocoa notes (16) KeyBoard

星期六, 五月 21st, 2011

KeyBoard Notifications(通过系统通知获得键盘的位置大小等)
UIKeyboardWillShowNotification
UIKeyboardDidShowNotification
UIKeyboardWillHideNotification
UIKeyboardDidHideNotification

可以通过UIKeyboardFrameBeginUserInfoKey 和 UIKeyboardFrameEndUserInfoKey,从userInfo的字典数据结构中获得键盘size和坐标的信息
应当每次处理这些信息,因为键盘所占用屏幕空间并不每次都一样(根据键盘的类型和定义)

显示键盘
一般来说,当用户选择可输入文本的视图时会自动弹出系统键盘,也可以通过编程方式,调出键盘(becomeFirstResponder相当于获得焦点,resignFirstResponder相当于失去焦点)

1
[textfield becomeFirstResponder];

隐藏键盘
和显示键盘不同,键盘不会自动隐藏,而需要开发者自行关闭

1
[myTextField resignFirstResponder];

当键盘弹出时挡住要输入内容位置时的处理
1. 获得键盘的位置和Size
2. 计算需要调整的高度
3. 将UIScrollView滚动到相应位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 在你的ViewController 某处调用这个方法注册notification方法

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(keyboardWasShown:)
            name:UIKeyboardDidShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self
             selector:@selector(keyboardWillBeHidden:)
             name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
 
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);

    scrollView.contentInset = contentInsets;

    scrollView.scrollIndicatorInsets = contentInsets;
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }

}

 

// Called when the UIKeyboardWillHideNotification is sent

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

相关源码
KeyboardAccessory

About Text, Web, and Editing Support in iOS

星期六, 五月 21st, 2011

https://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/Introduction/Introduction.html

gesture and transform

星期二, 五月 17th, 2011

read:
Layer Geometry and Transforms

sample code download:
Touches
SimpleGestureRecognizers

重要备忘

星期六, 五月 14th, 2011

例子:UserDefaultsDemo

Cocoa notes (15) Address Book

星期五, 五月 13th, 2011

CoreFoundation
平行于Foundation,基础类都有对应的类,Toll-Free Bridging = 基础数据类型和NS类的转换是没有损耗的

1
2
3
4
5
6
7
CFArrayRef array = ABAddressBookCopyPeopleWithName(...);
NSLog(@“%d”, [(NSArray *)array count]);
NSMutableArray *mutableArray = [(NSArray *)array mutableCopy];
[mutableArray release];
if (array) {
    CFRelease(array);
}

CoreFoundation使用NULL而不是nil

1
2
3
4
5
CFStringRef string = CreateSomeCFString...;
if (string != NULL) {
    DoSomethingWith(string);
    CFRelease(string);
}
1
2
3
NSString *string = (NSString *)CreateSomeCFString...;
NSLog(@“%@”, [string lowercaseString]);
[string autorelease]; // Even use autorelease!

ABAddressBookRef获得联系人名单

1
2
ABAddressBookRef ab = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyPeopleWithName(ab, name);

ABRecordRef
包括属性
■ First and last name
■ Image
■ Phone numbers, emails, etc…

单一属性,包括:
First Name, last name, birthday, etc…
get使用ABRecordCopyValue(…)方法

1
2
CFStringRef first =
    ABRecordCopyValue(person, kABPersonFirstNameProperty);

set使用ABRecordSetValue(…)方法

1
2
CFDateRef date = CFDateCreate();
ABRecordSetValue(person, kABPersonBirthdayProperty, date, &error);

多重属性(ABMultiValueRef),包括:
Phones, emails, URLs, etc…
类型用ABMultiValueRef表示,label/value

获得count

1
CFIndex count = ABMultiValueGetCount(multiValue);

获得value

1
CFTypeRef value = ABMultiValueCopyValueAtIndex(mv, index);

获得label

1
CFStringRef label = ABMultiValueCopyLabelAtIndex(mv, index);

获得identifier

1
CFIndex identifier = ABMultiValueGetIdentifierAtIndex(mv, index);

更新流程:
• 获取多重属性控制
• 增加值
• 将值赋予联系人
• 保存通讯录

1
2
3
4
5
ABMultiValueRef urls = ABRecordCopyValue(person, kABPersonURLProperty);
ABMutableMultiValueRef urlCopy = ABMultiValueCreateMutableCopy(urls);
ABMultiValueAddValueAndLabel(urlCopy, "the url", "social", NULL);
ABRecordSetValue(person, urlCopy, kABPersonURLProperty);
ABAddressBookSave(ab, &err);

排序
可使用内置的ABPersonGetSortOrdering,ABPersonComparePeopleByName,作为排序方法

1
2
3
4
5
CFMutableArrayRef people = // obtain an array of people
CFRange fullRange = CFRangeMake(0, CFArrayGetCount(people));
ABPersonSortOrdering sortOrdering = ABPersonGetSortOrdering();
CFArraySortValues(people, fullRange, ABPersonComparePeopleByName,
    (void*)sortOrdering);

或者使用objc的风格(下例中people是NSMutableArray)

1
[people sortUsingFunction:ABPersonComparePeopleByName context:(void*)sortOrdering];

获得联系人名字

1
2
3
ABRecordRef person = // get a person
CFStringRef name = ABRecordCopyCompositeName(person);
// do something clever with that person’s name

1
2
3
ABRecordRef person = // get a person
NSString *name = (NSString*)ABRecordCopyCompositeName(person);
// do something clever with that person’s name

ABPersonViewController属性
■ displayedPerson
■ displayedProperties
■ allowsEditing

ABUnknownPersonViewController属性
■ displayedPerson
■ allowsAddingToAddressBook
■ delegate

ABPeoplePickerNavigationController

1
2
3
4
5
6
    ABPeoplePickerNavigationController *ppnc = [[ABPeoplePickerNavigationController alloc] init];
    ppnc.peoplePickerDelegate = self;
    ppnc.displayedProperties = [NSArray arrayWithObject:[NSNumber numberWithInt:kABPersonEmailProperty]];
    ppnc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:ppnc animated:YES];
    [ppnc release];
1
2
3
4
5
6
7
8
// cancel选择
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker

// 当选择了通讯录的的某个联络人
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person

// 当选择了通讯录的某个联络人的某个属性
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier