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

相关文章
|
1月前
|
API 数据安全/隐私保护 iOS开发
利用uni-app 开发的iOS app 发布到App Store全流程
利用uni-app 开发的iOS app 发布到App Store全流程
85 3
|
3月前
|
存储 iOS开发
iOS 开发,如何进行应用的本地化(Localization)?
iOS 开发,如何进行应用的本地化(Localization)?
122 2
|
1天前
|
设计模式 存储 前端开发
Java从入门到精通:2.2.1学习Java Web开发,了解Servlet和JSP技术,掌握MVC设计模式
Java从入门到精通:2.2.1学习Java Web开发,了解Servlet和JSP技术,掌握MVC设计模式
|
7天前
|
API 定位技术 iOS开发
IOS开发基础知识:什么是 Cocoa Touch?它在 iOS 开发中的作用是什么?
【4月更文挑战第18天】**Cocoa Touch** 是iOS和Mac OS X应用的核心框架,包含面向对象库、运行时系统和触摸优化工具。它提供Mac验证的开发模式,强调触控接口和性能,涵盖3D图形、音频、网络及设备访问API,如相机和GPS。是构建高效iOS应用的基础,对开发者至关重要。
11 0
|
22天前
|
开发工具 Swift iOS开发
利用SwiftUI构建动态用户界面:iOS开发新范式
【4月更文挑战第3天】 随着苹果不断推进其软件开发工具的边界,SwiftUI作为一种新兴的编程框架,已经逐渐成为iOS开发者的新宠。不同于传统的UIKit,SwiftUI通过声明式语法和强大的功能组合,为创建动态且响应式的用户界面提供了一种更加简洁高效的方式。本文将深入探讨如何利用SwiftUI技术构建具有高度自定义能力和响应性的用户界面,并展示其在现代iOS应用开发中的优势和潜力。
|
1月前
|
iOS开发
iOS自动混淆测试处理笔记
iOS自动混淆测试处理笔记
12 0
|
2月前
|
设计模式 存储 前端开发
Java Web开发中MVC设计模式的实现与解析
Java Web开发中MVC设计模式的实现与解析
|
2月前
|
监控 API Swift
用Swift开发iOS平台上的上网行为管理监控软件
在当今数字化时代,随着智能手机的普及,人们对于网络的依赖日益增加。然而,对于一些特定场景,如家庭、学校或者企业,对于iOS设备上的网络行为进行管理和监控显得尤为重要。为了满足这一需求,我们可以利用Swift语言开发一款iOS平台上的上网行为管理监控软件。
196 2
|
2月前
|
iOS开发
  iOS 自动混淆测试处理笔记
  iOS 自动混淆测试处理笔记
|
3月前
|
数据可视化 iOS开发
iOS 开发,什么是 Interface Builder(IB)?如何使用 IB 构建用户界面?
iOS 开发,什么是 Interface Builder(IB)?如何使用 IB 构建用户界面?
40 4