iOS开发笔记 4、iOS中的Cocoa、设计模式等

简介: Cocoa中常用的类 NSStringNSMutableString 赋值 NSString *myString = @"some string"; NSString *myString = [NSStringstringWithFormat:@"object = %@",s...

Cocoa中常用的类

NSStringNSMutableString

赋值

NSString *myString = @"some string";

NSString *myString = [NSStringstringWithFormat:@"object = %@",someObject];

转换

NSString *upper = [myStringuppercaseString];

intintString = [myStringintValue];

去内容

NSString *trimmed = [myString string ByTrimmingCharactersInSet: [NSCharacterSet whitespace CharacterSet]];

截取字符串

NSString *aString = [numberStringsubstringToIndex:3];

NSRange range = NSMakeRange(4,3);

NSString *aString = [numberStringsubstringWithRange:range];

NSArray *arr = [numberString

componentsSeparatedByString:

 @" "];

替换

NSString *aString = [numberStringstringByReplacingOccurrencesOf

 String:@"three" withString: @"four"];

查找

NSRangefoundRange = [numberStringrangeOfString:@"two"];

BOOL found = ([numberStringrangeOfString:@"two"].location != NSNotFound);

文件

NSString *fileContents = [NSStringstringWithContentsOfFile:  @"myfile.txt"];

NSURL *url = [NSURL URLWithString: @"http://google.com"];

NSString *pageContents = [NSStringstringWithContentsOfURL:url];

Date Times

NSDate *myDate = [NSDate date];

NSTimeIntervalsecondsPerDay = 24*60*60;

NSDate *now = [NSDate date];

NSDate *yesterday = [now addTimeInterval:-secondsPerDay];

NSDateComponents *comp = [[NSDateCo m ponentsalloc] init];

[co m p setMonth:06];

[co m p setDay:01];

[co m p setYear:2010];

NSCalendar *myCal= [[NSCalendaralloc] initWithCalendarIdentifier: NSGregorianCalendar];

NSDate *myDate= [myCaldateFromComponents:comp];

NSArrayNSMutableArrayDictionary

NSString *string1 = @"one";

NSString *string2 = @"two";

NSString *string3 = @"three";

NSArray *myArray = [NSArrayarrayWithObjects:string1, string2, string3, nil];

for (NSString *obj in myArray) {

NSLog(@"%@",obj);

}

for (NSString *obj in [myArrayreverseObjectEnumerator])

{

NSLog(@"%@",obj);

}

NSArray *arr1 = [NSArrayarrayWith Objects:@"iPhone", @"iPod",nil];

NSDictionary *myDict = [[NSDictionar y alloc] dictionaryWithObjectsAndKeys: arr1, @"mobile", arr2, @"computers", nil];

for (id key in myDict) {

NSLog(@"key: %@, value: %@",

 key, [myDictobjectForKey:

 key]);

}

[myDict setObject:string2 forKey:@"media"];

NSNotification

Notifications provide a handy way for youto pass information between objects in your application without needing a direct reference between them. which contains a name, an object (often the object posting the notification), and an optional dictionary.

登记消息、消息处理方法、注销

[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(doSomething:)

 name:@"myNotification"

object:nil];

-(void)deallc

{

[[NSNotificationCenterdefaultCenter] removeObserver:self];

[superdealloc];

}

-(void)doSomething:(NSNotification*)aNote

{

NSDictionary *myDict = [aNoteobject];

NSLog(@”%@”, myDict);

}

发送消息

[[NSNotificationCenterdefaultCenter] postNotificationName:MY_NOTIFICATIONobject:myDict];

 

内存管理

iOS不支持GC,因此必须手动释放创建的对象[注意是创建者负责释放,像工厂方法的对象不需要调用者释放]

[object release];

Remember this basic rule of thumb: Any time you call the alloc, copy, or retainmethods on an object, you must at some point later call the release method.

THE AUTORELEASE ALTERNATIVE

If you’re responsible for the creation of an object and you’re going to pass it off to some other class for usage, you should autorelease the object before you send it off.

This is done with the autorelease method:

[objectautorelease];

You’ll typically send the autorelease message just before you return the object at the end of a method. After an object has been autoreleased, it’s watched over by a special NSAutoreleasePool. The object is kept alive for the scope of the method to which it’s been passed, and then the NSAutoreleasePool cleans it up.

-(NSString *)makeUserName

{

NSString *name = [[NSStringalloc] initWithString:@”new name”];

return [name autorelease];

}

如上例,返回的对象由NSAutoreleasePool负责释放,缺点是释放时刻不确定,没释放前占用系统的内存,调用者不用处理释放的问题,不过在使用retain方法时,必须调用配对的release,以平衡引用计数

使用UIKit库一个例子

UIButton *myButton = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

In most cases, the Cocoa Touch frameworks use a naming convention to help you decide when you need to release objects: If the method name starts with the word alloc, new, or copy, then you should call releasewhen you are finished with the object.

RETAINING AND COUNTING

What if you want to hold onto an object that has been passed to you and that will be autoreleased? In that case, you send it a retain message:

[object retain];

When you do this, you’re saying you want the object to stay around, but now you’ve become responsible for its memory as well: you must send a release message at some point to balance your retain.

image

Event response

bare events (or actions)

delegated events

notification

图书 iPhone and iPad in Action Chapter6 有详细的说明

 

设计模式

MVC

The Model View Controller (MVC) pattern separates an application’s data structures (the model) from its user interface (the view),with a middle layer (the controller) providingthe “glue” between the two. The controller takes input from the user (via the view), determines what action needs to be performed, and passes this to the model for processing. The controller can also act the otherway: passing information from the model to the view to update the user interface.

Delegate

The Delegate pattern is useful as an alternative to subclassing, allowing an object to define a method but assign responsibility for implementing that method to a different object (referred to as the delegate objector, more commonly, the delegate).

Delegates need not implement all (or even any) of the delegate methods for the source object. In that case, the source object’s default behavior for the method is often used.

下例通过委托改变了控件的行为[键盘不显示]

-(BOOL) textFieldShouldBeginEditing: (UITextField *)textField

{

return NO;

}

-(void)viewDidLoad {

CGRectrect = CGRectMake(10,10, 100,44);

UITextFiled *myTextField=[[UITextFieldalloc] initWithFrame:rect];

myTextField.delegate = self;

[self.viewaddSubView:myTextField];

[myTextField release];

}

Target-Action

下例展现了一个按钮的响应处理

-(void) buttonTap: (id)sender

{

NSLog(@”Button tapped”);

}

-(void)viewDidLoad{

….

[myButton addTerget:self action:@selector(buttonTap:) forControlEvents: UIControlEventTouchUpInside];

}

Categories

Like delegates, categories provide an alternative to subclassing, allowing you to add new methods to an existing class. The methods then become part of the class definition and are available to all instances (and subclasses) of that class.

image

image

上例给类UIImage增加了一个扩展的方法,这样调用者都可以调用这个方法,相比继承形式更轻量

Singletons

单实例,Cocoa中有很多的这个模式

float level = [[UIDevicecurrentDevice] batteryLevel];

 

程序生命期

image

相关文章
|
28天前
|
设计模式 缓存 前端开发
现代PHP开发中的设计模式应用与性能优化
本篇文章深入探讨了PHP开发中设计模式的实际应用及其对性能的影响。通过分析具体案例和最新研究成果,文章揭示了合理运用设计模式不仅可以提升代码的可维护性和扩展性,还能在特定场景下优化性能。我们将一起探索如何通过科学方法将设计模式融入日常开发实践,同时保持代码的高效执行。
|
1月前
|
设计模式 网络协议 Java
技术笔记:Reactor设计模式
技术笔记:Reactor设计模式
10 0
|
1月前
|
设计模式 存储 安全
技术好文共享:设计模式笔记:单件模式(Singleton)
技术好文共享:设计模式笔记:单件模式(Singleton)
15 0
|
2月前
|
设计模式
【设计模式】张一鸣笔记:责任链接模式怎么用?
【设计模式】张一鸣笔记:责任链接模式怎么用?
32 1
|
2月前
|
设计模式 存储 前端开发
Java的mvc设计模式在web开发中应用
Java的mvc设计模式在web开发中应用
|
2月前
|
设计模式 算法 Java
【设计模式系列笔记】设计模式与设计原则
设计模式,是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。 设计原则是一些通用的设计指导方针,它们提供了如何设计一个优秀的软件系统的基本思想和规则。指导着设计者如何组织代码以实现高内聚、低耦合、易扩展和易维护的软件系统。
47 4
|
2月前
|
设计模式 存储 前端开发
JS的几种设计模式,Web前端基础三剑客学习知识分享,前端零基础开发
JS的几种设计模式,Web前端基础三剑客学习知识分享,前端零基础开发
|
2月前
|
设计模式 算法 Java
设计模式在Java开发中的应用
设计模式在Java开发中的应用
29 0
|
2月前
|
设计模式 前端开发 API
写出易维护的代码|React开发的设计模式及原则
本文对React社区里出现过的一些设计模式进行了介绍,并讲解了他们遵循的设计原则。
|
2月前
|
设计模式 算法 搜索推荐
【PHP开发专栏】PHP设计模式解析与实践
【4月更文挑战第29天】本文介绍了设计模式在PHP开发中的应用,包括创建型(如单例、工厂模式)、结构型和行为型模式(如观察者、策略模式)。通过示例展示了如何在PHP中实现这些模式,强调了它们在提升代码可维护性和可扩展性方面的作用。设计模式是解决常见问题的最佳实践,但在使用时需避免过度设计,根据实际需求选择合适的设计模式。

热门文章

最新文章