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

相关文章

C#中读取XML文件的四种常用方法

《C#中读取XML文件的四种常用方法》Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具,下面我们就来看看C#中读取XML文件的方法都有哪些吧... 目录XML简介格式C#读取XML文件方法使用XmlDocument使用XmlTextReader/XmlTextWr

Python itertools中accumulate函数用法及使用运用详细讲解

《Pythonitertools中accumulate函数用法及使用运用详细讲解》:本文主要介绍Python的itertools库中的accumulate函数,该函数可以计算累积和或通过指定函数... 目录1.1前言:1.2定义:1.3衍生用法:1.3Leetcode的实际运用:总结 1.1前言:本文将详

CSS弹性布局常用设置方式

《CSS弹性布局常用设置方式》文章总结了CSS布局与样式的常用属性和技巧,包括视口单位、弹性盒子布局、浮动元素、背景和边框样式、文本和阴影效果、溢出隐藏、定位以及背景渐变等,通过这些技巧,可以实现复杂... 一、单位元素vm 1vm 为视口的1%vh 视口高的1%vmin 参照长边vmax 参照长边re

轻松上手MYSQL之JSON函数实现高效数据查询与操作

《轻松上手MYSQL之JSON函数实现高效数据查询与操作》:本文主要介绍轻松上手MYSQL之JSON函数实现高效数据查询与操作的相关资料,MySQL提供了多个JSON函数,用于处理和查询JSON数... 目录一、jsON_EXTRACT 提取指定数据二、JSON_UNQUOTE 取消双引号三、JSON_KE

MySQL数据库函数之JSON_EXTRACT示例代码

《MySQL数据库函数之JSON_EXTRACT示例代码》:本文主要介绍MySQL数据库函数之JSON_EXTRACT的相关资料,JSON_EXTRACT()函数用于从JSON文档中提取值,支持对... 目录前言基本语法路径表达式示例示例 1: 提取简单值示例 2: 提取嵌套值示例 3: 提取数组中的值注意

Python中操作Redis的常用方法小结

《Python中操作Redis的常用方法小结》这篇文章主要为大家详细介绍了Python中操作Redis的常用方法,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解一下... 目录安装Redis开启、关闭Redisredis数据结构redis-cli操作安装redis-py数据库连接和释放增

Java function函数式接口的使用方法与实例

《Javafunction函数式接口的使用方法与实例》:本文主要介绍Javafunction函数式接口的使用方法与实例,函数式接口如一支未完成的诗篇,用Lambda表达式作韵脚,将代码的机械美感... 目录引言-当代码遇见诗性一、函数式接口的生物学解构1.1 函数式接口的基因密码1.2 六大核心接口的形态学

一文详解Python中数据清洗与处理的常用方法

《一文详解Python中数据清洗与处理的常用方法》在数据处理与分析过程中,缺失值、重复值、异常值等问题是常见的挑战,本文总结了多种数据清洗与处理方法,文中的示例代码简洁易懂,有需要的小伙伴可以参考下... 目录缺失值处理重复值处理异常值处理数据类型转换文本清洗数据分组统计数据分箱数据标准化在数据处理与分析过

Java中Object类的常用方法小结

《Java中Object类的常用方法小结》JavaObject类是所有类的父类,位于java.lang包中,本文为大家整理了一些Object类的常用方法,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. public boolean equals(Object obj)2. public int ha

Java 字符数组转字符串的常用方法

《Java字符数组转字符串的常用方法》文章总结了在Java中将字符数组转换为字符串的几种常用方法,包括使用String构造函数、String.valueOf()方法、StringBuilder以及A... 目录1. 使用String构造函数1.1 基本转换方法1.2 注意事项2. 使用String.valu