Monthly Archives: 七月 2012

Hello World

ios开发入门—-view的简单使用

向视图中添加一个控件:

 UIScrollView *weatherBack = [[UIScrollView alloc]
	initWithFrame:CGRectMake(100, 100, 100, 139)];
 //背景色   
[weatherBack setBackgroundColor:[UIColor colorWithRed:
	255 green:0 blue:0 alpha:0.5]];
//滚动范围
[weatherBack setContentSize:CGSizeMake(421, 139)];
 //放入view  
 [[self view]addSubview:weatherBack]; 
//addsubview会自动retrain,所以这里要四方
[weatherBack release];

向控件中添加控件:

 UILabel* weekL = [[UILabel alloc] initWithFrame:
	CGRectMake(5, 3, 50, 30)];            
[weekL setText:@”星期三”];            
[weekL setFont:[UIFont fontWithName:
	@"Helvetica-Bold" size:16]];            
[weekL setBackgroundColor:[UIColor colorWithRed:
	0 green:0 blue:0 alpha:0]];            
[weekL setTextColor:[UIColor colorWithRed:
	255 green:0 blue:0 alpha:0.9]];
//将label添加到父节点中            
[text addSubview:weekL];
[weekL release];

响应事件:

//新建一个按钮
UIButton* testB = [[UIButton alloc] initWithFrame:
	CGRectMake(75, 85, 80, 20)];            
[testB setTitle:@"test" forState:UIControlStateNormal];
//将[self testButton]方法 绑定到UIControlEventTouchUpInside
[testB addTarget:self action:@selector(testButton:)
	forControlEvents:UIControlEventTouchUpInside];            
[text addSubview:testB];            
[testB release];

testButton的定义:

//事件处理方法
-(IBAction)testButton:(id)sender{    
	UIAlertView *alert = [[UIAlertView alloc]initWithTitle:
		@"hello" message:nil delegate:self
 		cancelButtonTitle:@"取消" 			
		otherButtonTitles:@"确定",
		nil];   
	[alert show];    
	[alert release];
}

以上操作,都可以在xcode自带的“所见即所得”工具“IB”中完成,在书本和网上找到的入门教程也都是使用IB,但大部分时候,我们仍然需要使用代码来做这些工作
————

Hello World

NSNotificationCenter 的使用

1. 定义一个方法

      -(void) update{       
             //...
      }

2. 对象注册,并关连消息

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update) name:@"gotoupdate" object:nil]

3. 在要发出通知消息的地方

     [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoupdate" object:nil];

每个运行中的application都有一个NSNotificationCenter的成员变量,它的功能就类似公共栏. 对象注册关注某个确定的notification(如果有人捡到一只小狗,就去告诉我). 我们把这些注册对象叫做 observer. 其它的一些对象会给center发送notifications(我捡到了一只小狗). center将该notifications转发给所有注册对该notification感兴趣的对象. 我们把这些发送notification的对象叫做 poster
Notification 就是设计模 式中的 观察者模式, cocoa为我们实现了该模式


———————————
2012.7.11

刚发现一个严重的问题,如果使用addObserver多次注册同一个方法,再通过postNotificationName调去方法,这个方法会被执行多次!
解决的方法,是在方法调用以后,通过removeObserver方法解除注册

     -(void) update{
          [[NSNotificationCenter defaultCenter]removeObserver:self name:@"gotoupdate" object:nil];
          //...
     }