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

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

JS常用组件收集

收集了一些平时遇到的前端比较优秀的组件,方便以后开发的时候查找!!! 函数工具: Lodash 页面固定: stickUp、jQuery.Pin 轮播: unslider、swiper 开关: switch 复选框: icheck 气泡: grumble 隐藏元素: Headroom

hdu1171(母函数或多重背包)

题意:把物品分成两份,使得价值最接近 可以用背包,或者是母函数来解,母函数(1 + x^v+x^2v+.....+x^num*v)(1 + x^v+x^2v+.....+x^num*v)(1 + x^v+x^2v+.....+x^num*v) 其中指数为价值,每一项的数目为(该物品数+1)个 代码如下: #include<iostream>#include<algorithm>

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

常用的jdk下载地址

jdk下载地址 安装方式可以看之前的博客: mac安装jdk oracle 版本:https://www.oracle.com/java/technologies/downloads/ Eclipse Temurin版本:https://adoptium.net/zh-CN/temurin/releases/ 阿里版本: github:https://github.com/

在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern) 确保一个类只有一个实例,并提供一个全局访问点。 示例代码: class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;this.data = [];}addData(value)

安卓链接正常显示,ios#符被转义%23导致链接访问404

原因分析: url中含有特殊字符 中文未编码 都有可能导致URL转换失败,所以需要对url编码处理  如下: guard let allowUrl = webUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {return} 后面发现当url中有#号时,会被误伤转义为%23,导致链接无法访问

30常用 Maven 命令

Maven 是一个强大的项目管理和构建工具,它广泛用于 Java 项目的依赖管理、构建流程和插件集成。Maven 的命令行工具提供了大量的命令来帮助开发人员管理项目的生命周期、依赖和插件。以下是 常用 Maven 命令的使用场景及其详细解释。 1. mvn clean 使用场景:清理项目的生成目录,通常用于删除项目中自动生成的文件(如 target/ 目录)。共性规律:清理操作

C++操作符重载实例(独立函数)

C++操作符重载实例,我们把坐标值CVector的加法进行重载,计算c3=c1+c2时,也就是计算x3=x1+x2,y3=y1+y2,今天我们以独立函数的方式重载操作符+(加号),以下是C++代码: c1802.cpp源代码: D:\YcjWork\CppTour>vim c1802.cpp #include <iostream>using namespace std;/*** 以独立函数

019、JOptionPane类的常用静态方法详解

目录 JOptionPane类的常用静态方法详解 1. showInputDialog()方法 1.1基本用法 1.2带有默认值的输入框 1.3带有选项的输入对话框 1.4自定义图标的输入对话框 2. showConfirmDialog()方法 2.1基本用法 2.2自定义按钮和图标 2.3带有自定义组件的确认对话框 3. showMessageDialog()方法 3.1