IOS常用的类 函数 COCOA 设计模式

2024-03-28 22:18

本文主要是介绍IOS常用的类 函数 COCOA 设计模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Cocoa中常用的类

NSStringNSMutableString

赋值

NSString *myString = @"some string";

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

mystring = [NSString stringWithString:aString];

Returns a string created by copying the characters from another given string.

转换

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"];

利用@后面的字符串 创建和返回一个URL对象

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

这篇关于IOS常用的类 函数 COCOA 设计模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/856835

相关文章

Android Kotlin 高阶函数详解及其在协程中的应用小结

《AndroidKotlin高阶函数详解及其在协程中的应用小结》高阶函数是Kotlin中的一个重要特性,它能够将函数作为一等公民(First-ClassCitizen),使得代码更加简洁、灵活和可... 目录1. 引言2. 什么是高阶函数?3. 高阶函数的基础用法3.1 传递函数作为参数3.2 Lambda

Linux上设置Ollama服务配置(常用环境变量)

《Linux上设置Ollama服务配置(常用环境变量)》本文主要介绍了Linux上设置Ollama服务配置(常用环境变量),Ollama提供了多种环境变量供配置,如调试模式、模型目录等,下面就来介绍一... 目录在 linux 上设置环境变量配置 OllamPOgxSRJfa手动安装安装特定版本查看日志在

Java常用注解扩展对比举例详解

《Java常用注解扩展对比举例详解》:本文主要介绍Java常用注解扩展对比的相关资料,提供了丰富的代码示例,并总结了最佳实践建议,帮助开发者更好地理解和应用这些注解,需要的朋友可以参考下... 目录一、@Controller 与 @RestController 对比二、使用 @Data 与 不使用 @Dat

Mysql中深分页的五种常用方法整理

《Mysql中深分页的五种常用方法整理》在数据量非常大的情况下,深分页查询则变得很常见,这篇文章为大家整理了5个常用的方法,文中的示例代码讲解详细,大家可以根据自己的需求进行选择... 目录方案一:延迟关联 (Deferred Join)方案二:有序唯一键分页 (Cursor-based Paginatio

C++中::SHCreateDirectoryEx函数使用方法

《C++中::SHCreateDirectoryEx函数使用方法》::SHCreateDirectoryEx用于创建多级目录,类似于mkdir-p命令,本文主要介绍了C++中::SHCreateDir... 目录1. 函数原型与依赖项2. 基本使用示例示例 1:创建单层目录示例 2:创建多级目录3. 关键注

Python实现常用文本内容提取

《Python实现常用文本内容提取》在日常工作和学习中,我们经常需要从PDF、Word文档中提取文本,本文将介绍如何使用Python编写一个文本内容提取工具,有需要的小伙伴可以参考下... 目录一、引言二、文本内容提取的原理三、文本内容提取的设计四、文本内容提取的实现五、完整代码示例一、引言在日常工作和学

Redis中的常用的五种数据类型详解

《Redis中的常用的五种数据类型详解》:本文主要介绍Redis中的常用的五种数据类型详解,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Redis常用的五种数据类型一、字符串(String)简介常用命令应用场景二、哈希(Hash)简介常用命令应用场景三、列表(L

C++中函数模板与类模板的简单使用及区别介绍

《C++中函数模板与类模板的简单使用及区别介绍》这篇文章介绍了C++中的模板机制,包括函数模板和类模板的概念、语法和实际应用,函数模板通过类型参数实现泛型操作,而类模板允许创建可处理多种数据类型的类,... 目录一、函数模板定义语法真实示例二、类模板三、关键区别四、注意事项 ‌在C++中,模板是实现泛型编程

kotlin的函数forEach示例详解

《kotlin的函数forEach示例详解》在Kotlin中,forEach是一个高阶函数,用于遍历集合中的每个元素并对其执行指定的操作,它的核心特点是简洁、函数式,适用于需要遍历集合且无需返回值的场... 目录一、基本用法1️⃣ 遍历集合2️⃣ 遍历数组3️⃣ 遍历 Map二、与 for 循环的区别三、高

python中time模块的常用方法及应用详解

《python中time模块的常用方法及应用详解》在Python开发中,时间处理是绕不开的刚需场景,从性能计时到定时任务,从日志记录到数据同步,时间模块始终是开发者最得力的工具之一,本文将通过真实案例... 目录一、时间基石:time.time()典型场景:程序性能分析进阶技巧:结合上下文管理器实现自动计时