iOS学习笔记总结版

iOS学习笔记

Xcode环境配置

  • icloud账号配置

    1. 打开Xcode -> Preferences -> Accounts -> 左下角 + -> App ID -> 输入账号密码进行认证
    2. 选择manage certificates
    3. 输入账号/密码
    4. 点击+ 新增
  • 证书导入

    1. 在 .xcodeproj中, 配置bundle ID, 导入provisioning profile证书 xxxx.provision
    2. 手机需要在apple develop官网上的对应证书新增设备uuid
    3. development.cer
  • cocopods

    # 安装pod
    sudo gem install cocoapods
    
    # 查看可更新的库
    pod outdated
    
    # 仅更新指定库
    pod update AMapFoundation --verbose --no-repo-update
    
    
    pod 'AFNetworking', '= 2.0'
    

基础语法

.h 声明文件

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    NSString *_name;
    int _age;
}
// 方法声明
-(void)run;
-(void)eat:(NSString *)foodName;
-(int)sum:(int)num1:(int)num2;

// 静态方法
+(NSString *)getAFuncName: (NSString *) funcName withParams:(NSString *)param;
@end

.m 实现文件

#import <Foundation/Foundation.h>

@implementation Porson
// 实现在interface中声明的方法
  // 不带参数
  -(void)run{
    NSLog(@"this is eate");
  }
  // 带一个参数
  -(void)eat:(NSString *)foodName{
      NSLog(@"%@真好吃!",foodName);
  }
	// 带多个参数
	-(int)sum:(int)num1:(int)num2{
		int num3 = num1 + num2;
    return num3;
  }
	// 为增强可读性 可以写成
	-(int)sumWithNum1:(int)num1 andNum2:(int)num2{}
    
  // 静态方法 带多个参数
  +(NSString *)getAFuncName: (NSString *) funcName withParams:(NSString *)param{
    return @"FuncName"
  }

 @end

int main(int argc, const char * argv[])
{
    // 调用一个静态方法alloc来分配内存, 创建一个该对象的指针指向刚创建的内存空间
    Porson *p1 = [Porson alloc];
    p1 = [p1 init];
    // 以上两步可以合并为
		Porson *p1 = [[Porson alloc] init];

    p1->_name = @"Barry";
   	[p1 run]
    [p1 eat:@"红烧肉"];
   	[p1 sumWithNum1:10 andNum2:10];
  
}

Student *stu= [Student new];//相当于Student *stu = [[Student alloc] init]

@property int age;//编译器遇到@property时,会生动生成set/get方法的声明 只用在.h文件里,用于声明方法(set/get)

// 内存释放
Car *car = [[[Car alloc] initWithSize:10 andPrice:23.0f] autorelease];

[person release];

// set/get的实现
@synthesize age,_no,height;//相当于三个成员变量的实现
[若用synthesize了,即可在.h文件中不写成员变量age,_no,height,会默认去访问与age同名的变量,若找不到同名的变量,会自动生成一个同名变量,并且若自己定义的成员变量的名字与@synthesize不一样时,会默认创建自动生成的]

@property (nonatomic,getter=isEnable) BOOL enable;//指定get的方法名;

WKScriptMessageHandler实现js调用原生方法

// 添加代理, 注册方法名
[_webView.configuration.userContentController addScriptMessageHandler:self name:@"这是约定好的回调方法名"];

// 实现协议方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
   if ([message.name isEqualToString:@"约定好的方法名"]) {
       ///js 传来的参数
       NSDictionary *body = message.body;
    ...
   }
}

// js 调用
window.webkit.messageHandlers.约定好的方法名.postMessage(message)

修饰符

  • 读写属性:readwrite/readonly;

    readwrite(默认),生成set/get;

    readonly:只生成get方法

  • 引用属性:assign/retain/copy/strong;

    assign(默认):直接赋值;

    retain:引用+1;

    strong:指定该属性为强引用,这意味着在对象引用该属性时,该属性将保持有效,直到对象释放或将其引用设为nil。强引用通常用于对象之间的关联,例如一个对象拥有另一个对象。

  • 原子性:atomic/nonatomic;

    atomic(默认): 加锁,提供了多线程安全;

    nonatomic:禁止多线程,变量保护,可提高性能;[对于在iPhone这个小型设备上,内存很小,默认情况下不需要考虑太多的多线程,以提高性能]

语法

NSString常用操作
// 带变量的字符串定义
NSString *stringName = [NSString stringWithFormat: @"content: %@", content];
// 字符串长度
[stringName length]| stringName.length;
// 获取字符串对应位置字符
unichar c = [stringName characterAtIndex:0];

// 判断值是否相等
if([stringName isEqualToString:@"get"]){...}
  
// 截取字符串 从第一位开始截到最后
NSString *substring = [@"abcdefg" substringFromIndex: 1]; //bcedefg
// 截取到第一位
NSString *substring1 = [@"abcdefg" substringToIndex:1]; // a
// 截取指定长度
NSString *substring2 = [@"abcdefg" substringWithRange:NSMakeRange(1, 2)]; // bc

// 拼接
NSString *appendString = [@"abc" stringByAppendingString:@"def"]; // abcdef
NSString *appendString1 = [@"abc" stringByAppendingFormat:@"%d",123]; // abc123
// 拆分字符串
[stringname componentsSeparatedByString:@"**|**"]

// 字符串替换
NSString *contentString = @"hello world";
NSRange range = [contentString rangeOfString:@"hello"]; // 获取hello在字符串中的位置 
// 判断是否包含某字符串
[urlString rangeOfString: key].location == NSNotFound
  
if (range.length != 0) {
  //替换该范围的字符串为@“hi”
  NSString *replaceString = [contentString stringByReplacingCharactersInRange:range withString:@"hi"];
}

NSString *replaceString1 = [contentString stringByReplacingOccurrencesOfString:@"hello" withString:@"hi"];

//字符串类型转换成int类型
NSInteger number = [@"123" intValue];
// 其他类型转化为字符串
NSString *other = [NSString stringWithFormat:@"%ld",number];
//把小写的字符串转换成大写
NSString *uppercaseString = [@"abc" uppercaseString];
//把上一句大写的字符串转换成小写
NSString *lowercaseString = [uppercaseString lowercaseString];

// 字符串前缀后缀判断
[@"abcdef" hasPrefix:@"abc"]
[@"abcdef" hasSuffix:@"def"]

// 读取文件
NSString *jsPath = [[NSBundle mainBundle] pathForResource:@"tjapp" of	Type:@"js"];
NSString *jsString = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:nil];

NSMutableNString
//在堆区开辟空间创建可变字符串。
NSMutableString *string1 = [[NSMutableString alloc]initWithString:@"abcdefg"];
//也可以使用便利构造器创建
NSMutableString *string2 = [NSMutableString stringWithFormat:@"abcdefg"];
//在原字符串上直接追加字符串
[string1 appendString:@"asdf"];
//在原字符串上直接追加格式化字符串
[string2 appendFormat:@"%d",123];
//插入字符串
//将一个字符串插入到一个索引位置处
[string1 insertString:@"www." atIndex:0];
//删除指定位置的字符:1是索引,2是长度
[string1 deleteCharactersInRange:NSMakeRange(1, 2)];
NSDictionary
// 初始化 先写value,再写key,一对key-value是一个元素,nil作为字典存放元素的结束标志。
NSDictionary *num = [[NSDictionary alloc] initWithObjectsAndKeys:@"one", @"num1", @"two", @"num2", @"three", @"num3", nil];
NSDictionary *num1 = [NSDictionary dictionaryWithObjectsAndKeys:@"one",@"num1",@"two",@"num2",nil];
NSDictionary *num2 = @{
  @"num1":@"one",
  @"num2":@"two"
};

NSLog(@"dict3----->%@",dict3);

// 获取键值对个数
NSInteger count = [dict3 count];
// 获取所有key
NSArray *arr = [dict3 allKeys];
// 获取所有值
NSArray *arr1 = [dict3 allValues];
// 根据key获取值
NSString *string = [dict3 objectForKey:@"num1"];

NSMutableDictionary
//初始化方法
NSMutableDictionary *name = [[NSMutableDictionary alloc] initWithCapacity:0];
NSMutableDictionary *name1 = [NSMutableDictionary dictionaryWithCapacity:0];
NSMutableDictionary *name2 = [@{@"key1":@"frank", @"key2":@"duck"} mutableCopy];
NSMutableDictionary *name0 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"one",@"num1",@"two",@"num2", nil];

// 常用操作
//修改已有键对应的值,如果键不存在,则为添加键值对,如果键存在,则为修改已有键对应的值
[name2 setObject:@43 forKey:@"age"];

//移除指定的键对应的键值对
[name2 removeObjectForKey:@"age"];
NSLog(@"%@",name2);

// 判断是否有某个KEY
isContain = [dic objectForKey:@"key1"]

//移除字典中所有的键值对
[name2 removeAllObjects];
NSLog(@"%@",name2);
  • 遍历字典
// for in
for (NSString *key in dict3) {
    NSLog(@"%@",key);
    //[dic objectForKey:key];
    NSLog(@"%@",dic[key]);
}

//把字典中的键放到一个数组中,name age score
NSArray *keyArr= [dic allKeys];
 //遍历这个数组
 for (int i=0; i<keyArr.count; i++) {
     NSLog(@"%@",[dic objectForKey:keyArr[i]]);
 }

NSEnumerator *enumKeys = [aDic keyEnumerator];
for (NSObject *obj in enumKeys){
  NSLog(@"enumKey: %@", obj);
}

NSEnumerator *enumValues = [aDic objectEnumerator];
for (NSObject *obj in enumValues){
  NSLog(@"value in dict: %@", obj);
}
  • json转化为字典

    NSDictionary *params = [NSJSONSerialization JSONObjectWithData: [message.body dataUsingEncoding: NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    
  • json转化为字符串

    NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:rlt options:0 error:&err]encoding:NSUTF8StringEncoding];
    
NSArray
  • 初始化
NSArray *arrayname = [[NSArray alloc] initWithObjects:@"aaa", @"bbb", @"ccc", nil];
NSArray *number1 = [NSArray arrayWithObjects:@"one",@"two",@"three", nil]; //便利构造器
NSArray *number2 = @[@"one",@"two",@"three"]; // 字面量形式
  • 常用方法
// 数组长度
NSInteger count = [arrayname count];
// 获取指定下标元素
NSString *arrayItem = [arrayname objectAtIndex:1];
// 返回元素的下标
NSUInteger loc = [arrayname indexOfObject:@"three"];
// 判断数组是否包含某元素
if ( [arrayname containsObject:@"one"] ){...}
// 将数组拼接为字符串
NSString *string1 = [arrayname componentsJoinedByString:@"&"];
// 字符串拆分为数组
NSArray *array = [stringname componentsSeparatedByString:@"."];
NSMutableArray
  • 初始化
NSMutableArray *name = [[NSMutableArray alloc] initWithCapacity:0];
NSMutableArray *name1 = [NSMutableArray arrayWithCapacity:0];
NSMutableArray *name2 = [@[@"frank", @"duck", @"monkey", @"cow"] mutableCopy];
  • 可变数组的常用方法
//数组中添加一个对象
[arrayname addObject:@"cat"];
//数组中指定位置插入一个对象
[arrayname insertObject:@"dog" atIndex:1];
//数组中移除一个对象
[arrayname removeObject:@"cat"];
//移除数组中最后一个对象
[arrayname removeLastObject];
//移除数组中所有的元素
[arrayname removeAllObjects];
//数组中移除指定位置的元素
[arrayname removeObjectAtIndex:2];
//使用指定的对象替换指定位置的对象
[arrayname replaceObjectAtIndex:2 withObject:@"hhhh"];
//交换指定的两个下标对应的对象
[arrayname exchangeObjectAtIndex:1 withObjectAtIndex:2];

NSLog(@"%@", array);
  • 遍历数组
//1、通过索引遍历数组
for(NSInterger i = 0; i < [arrayName count]; i++){
  NSLog(@"result:%@", [array objectAtIndex:i]);
}

//2、使用NSEnumerator遍历数组
NSEnumerator *enumerator = [array objectEnumerator];
id thingie;
while(thingie = [enumerator nextObject])
{
  NSLog(@"I found %@",thingie);
}

//3、使用快速枚举遍历数组
NSString *object;
for(object in array)
{
  NSLog(@"%@",object);
}
NSUserDefault

NSUserDefaults 适合存储轻量级的不需要加密的本地数据,例如用户的偏好设置、用户名等

NSString *clouds = [[NSUserDefaults standardUserDefaults] valueForKey:CLOUDS];

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//存数据
[userDefaults setObject:@"名字" forKey:@"name"];
//取数据
NSString *name = [userDefaults objectForKey:@"name"];
//移除数据
[userDefaults removeObjectForKey:@"name"];

// 获取本地数据存储的值
if([[NSUserDefaults standardUserDefaults] objectForKey:@"message"]==nil){
[[NSUserDefaults standardUserDefaults] setObject:@"This is message" forKey:@"message"];
 [[NSUserDefaults standardUserDefaults] synchronize];
}

全局变量

// 赋值 
[GlobalObj sharedInstance].AAAA = NO;

// 使用
[GlobalObj sharedInstance].AAAA;

常用方法

dispatch_async

​ 为了避免界面在处理耗时的操作时卡死,比如读取网络数据,IO,数据库读写等,我们会在另外一个线程中处理这些操作,然后通知主线程更新界面。

  • dispatch_async: 调用一个block,这个block会被放到指定的queue队尾等待执行, dispatch_async会马上返回

  • dispatch_sync: 使用dispatch_sync 同样也是把block放到指定的queue上面执行,但是会等待这个block执行完毕才会返回,阻塞当前queue直到sync函数返回。

// 调用一个block,这个block会被放到指定的queue队尾等待执行
dispatch_async(dispatch_get_main_queue(), ^{
  // 内部为需要异步执行的代码
   NSLog(@"main queue");
   self.label = [UILabel new];
 });

功能

弹窗

// 弹出提示框
+(void)
UIAlertController *errorAlertController = [UIAlertController alertControllerWithTitle:@"" message:@"初始化失败" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler: nil];

[errorAlertController addAction:sure];

[[ControllerHelper topNavigationController] presentViewController:errorAlertController animated:YES completion:nil];

自定义request请求

    NSURL *url1 = [NSURL URLWithString:@"https://baidu.com"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url1 cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:60];
    

快捷键

格式化:crtl+i
按文件名查找: commnad+shfit+o
找到当前文件在导航栏位置: command+shift+j

常用iOS原生方法

// String转化URL   
    NSURL *url = [NSURL URLWithString:@"https://www.example.com"];

 // JSON转Dictionary
       NSData *jsonData = [messageJsonString dataUsingEncoding:NSUTF8StringEncoding];
       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];

// 方法命名约定
- (void)insertObject: (id)anObject atIndex: (NSInteger)otherIndex
参数1:anObject   参数2: otherIndex  返回类型: void (无返回值)
 - 表示实例方法  +表示类方法

全局引入文件

.pch文件中添加

页面白屏问题

 // 对于特殊延迟js加载时间
if(YES){
    WKUserScript *script = [[WKUserScript alloc] initWithSource:jsString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [userCC addUserScript:script];
}else{
    WKUserScript *script = [[WKUserScript alloc] initWithSource:jsString injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
    [userCC addUserScript:script];
}

清除缓存

删除该目录文件 ~/Library/Developer/Xcode/DerivedData

进阶知识

应用生命周期

口 Not running(非运行状态)。应用没有运行或被系统终止。

口 Inactive(前台非活动状态)。应用正在进入前台状态,但是还不能接受事件处理。

口 Active(前台活动状态)。应用进入前台状态,能接受事件处理。

口 Background(后台状态)。应用进入后台后,依然能够执行代码。如果有可执行的代码,就会执行代码,如果没有可执行的代码或者将可执行的代码执行完毕,应用会马上进入挂起状态。

口 Suspended(挂起状态)。被挂起的应用进入一种“冷冻”状态,不能执行代码。如果系统内存不够,应用会被终止。


didFinishLaunchingWithOptions: 应用启动并进行初始化时会调用该方法并发出通知。这个阶段会实例化根视图控制器

applicationDidBecomeActive: 应用进入前台并处于活动状态时调用该方法并发出通知。这个阶段可以恢复UI的状态(例如游戏状态等)

applicationwillResignActive:应用从活动状态进入到非活动状态时调用该方法并发出通知。这个阶段可以保存UI的状态(例如游戏状态等)

applicationDidEnterBackground: 应用进入后台时调用该方法并发出通知。这个阶段可以保存用户数据,释放一些资源(例如释放数据库资源等)

applicationwillEnterForeground:应用进入到前台,但是还没有处于活动状态时调用该方法并发出通知。这个阶段可以恢复用户数据

applicationwillTerminate: 应用被终止时调用该方法并发出通知,但内存清除时除外。这个阶段释放一些资源,也可以保存用户数据。强制杀后台时能否调用到?

唤端技术(deep link技术)

  • URL Scheme(Android、IOS通用)

    • 方法一:提供专属页面

H5提供网页,每个不同的功能提供不同的网页,服务端返回这些网页的URL,客户端配置打开 URL Scheme ,然后使用 Safari 直接加载URL

网页中根据进入方式的不同,自动重定向打开APP的 URL Scheme。

  • 方法二:提供通用页面

H5提供通用的网页,客户端替换通用网页中的内容,比如标题、图标等,并转为 DataURI 格式,服务端提供接口 URL,客户端配置打开 URL

Scheme,使用 Safari 加载,接口返回强制重定向加载 DataURI 数据

这种方式是一种比较通用的技术,有点像 web 中我们通过域名定位到一个网站,app 同样是通过类似的这个东西(URL Scheme)来定位到 app。各平台的兼容性也很好,它一般由协议名、路径、参数组成。这个一般是由Native开发的人员提供,我们前端开发人员再拿到这个scheme之后,就可以用来打开APP或APP内的某个页面了。

常用APP的 URL Scheme

APP微信支付宝淘宝QQ知乎
URL Schemeweixin://alipay://taobao://mqq://zhihu://

其中scheme既可以是 IOS 中常见的协议,也可以是我们自定义的协议。IOS 中常见的协议包括tel协议、http协议等,自定义协议可以使用自定义的字符串,当我们启动第三方的应用时候,多是使用自定义协议。

H5打开方式

常用的有以下这几种方式

  • 直接通过window.location.href跳转
window.location.href = 'WeiXin://'
  • 通过iframe跳转
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
iframe.src = 'WeiXin://'
document.body.appendChild(iframe)
  • 直接使用a标签进行跳转

  • 通过js bridge来打开

window.Bridge.call('openApp', {url: 'WeiXin://'})

使用场景

  1. 服务器下发跳转路径,客户端根据服务器下发跳转路径跳转相应的页面
  2. H5页面点击锚点,根据锚点具体跳转路径APP端跳转具体的页面
  3. APP端收到服务器端下发的PUSH通知栏消息,根据消息的点击跳转路径跳转相关页面
  4. APP根据URL跳转到另外一个APP指定页面
  • Universal Link (iOS)

Universal Link 是在iOS 9中新增的功能,使用它可以直接通过https协议的链接来打开 APP。 它相比前一种URL Scheme的优点在于它是使用https协议,所以如果没有唤端成功,那么就会直接打开这个网页,不再需要判断是否唤起成功了。并且使用 Universal Link,不会再弹出是否打开的弹出,对用户来说,唤端的效率更高了。

原理

  • 在 APP 中注册自己要支持的域名;
  • 在自己域名的根目录下配置一个 apple-app-site-association 文件即可。(具体的配置前端同学不用关注,只需与iOS同学确认好支持的域名即可)

nil、Nil、NSNull和NULL

  • nil

用来表示一个对象是空对象,即想要表示此对象不存在。给对象赋值时一般会使用object = nil,表示想把这个对象释放掉;或者对象引用计数器为0了,系统将这块内存释放掉,这个时候这个对象被置为nil。

  • Nil

是用来表示一个类是空类。比如:Class myClass = Nil。和nil没有明确的区分,也就是说凡是使用nil的地方都可以用Nil来代替,反之亦然。约定俗成地将nil表示一个空对象,Nil表示一个空类。

  • NULL是在C/C++中的空指针,在C语言中,NULL是无类型的,只是一个宏,它代表空。C语言中,当我们使用完一个指针以后,通常会设置其指向NULL。如果没有设置,这个指针就成了所谓的野指针,然后其它地方不小心访问了这个指针是很容易造成非法访问的,常见的表现就是崩溃了。

Objective-C是基于C语言的面向对象语言,那么也会使用到C语言类型的指针,比如使用const char *类型,判断是否为空时,是使用p != NULL来判断的。

  • NSNull是继承于NSObject的类型。它是很特殊的类,它表示是空,什么也不存储,但是它却是对象,只是一个占位对象。

它的使用场景跟nil是不一样的,比如说服务端接口中,要求我们在值为空时,必须传入空值,就可以这样:

NSDictionry *parameters = @{@"arg1": @"value1", @"arg2": arg2.isEmpty ? [NSNull null] : "arg2"};

NSNull 和 nil 的区别:nil是一个空对象,已经完全从内存中消失了;而NSNull为“值为空的对象”,这个类是继承NSObject,并且只有一个“+ (NSNull *) null;”类方法。(这就说明NSNull对象拥有一个有效的内存地址,所以在程序中对它的任何引用都是不会导致程序崩溃的。)

协议传值

  1. 声明协议,自定义声明一个协议方法
  2. 声明代理人属性
  3. 遵守协议
  4. 设置代理
  5. 实现协议方法
  6. 执行协议方法
//SecondViewController.h 文件中
#import <UIKit/UIKit.h>
//第1步 声明协议
@protocol  PassValueDelegate <NSObject>
//自定义协议方法
- (void)passContent:(NSString *)content;
@end

@interface SecondViewController : UIViewController
@property UITextField *textfield;
//第2步 声明代理人属性
@property id<PassValueDelegate> delegate;
@end
---------

//FirstViewController.m文件中
#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController ()
//第3步 签订协议
<PassValueDelegate>
@end

@implementation FirstViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btn.frame = CGRectMake(140, 210, 100, 40);
    [_btn setTitle:@"下一页" forState:UIControlStateNormal];
    [_btn addTarget:self action:@selector(pressNext) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btn];
    _content = [[UILabel alloc] initWithFrame:CGRectMake(140, 160, 200, 40)];
    _content.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_content];            
}

- (void)pressNext {
    SecondViewController *secondView = [[SecondViewController alloc] init];
    //第四步 设置代理
    secondView.delegate = self;
    [self presentViewController:secondView animated:YES completion:nil];
}

//第五步 实现协议方法
- (void)passContent:(NSString *)content {
    _content.text = content;
}
----------------

//在SecondViewController.m 文件中
#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _textfield = [[UITextField alloc] initWithFrame:CGRectMake(50, 130, 300, 40)];
    _textfield.borderStyle = UITextBorderStyleLine;
    [self.view addSubview:_textfield];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    backBtn.frame = CGRectMake(100, 210, 100, 40);
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(pressBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
}
- (void)pressBack {
    //第6步  执行协议方法
    [self.delegate passContent:_textfield.text];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

present 和Push的区别

二者都可以推出新界面,但是方式不一样

present与dismiss对应, push与pop对应

present只能逐级返回,push所有视图由视图栈控制,可以返回上一级,也可以返回到根vc,其他vc

调试问题:

右键 findxxxz selector找到函数方法的调用栈
引入sdk时,出现找不到link的问题,build pharese里看下是否正确引入,然后clean build一下缓存

XCode14 Charts报错:Type ‘ChartDataSet’ does not conform to protocol ‘RangeReplaceableCollection’

// MARK: RangeReplaceableCollection

extension ChartDataSet: RangeReplaceableCollection 方法里补充

 public func replaceSubrange<C>(_ subrange: Swift.Range<Int>, with newElements: C) where C :
 	Collection, ChartDataEntry == C.Element {
 }


source="\$(readlink "\${source}")"
替换为
source="\$(readlink -f "\${source}")"

内存泄露问题

// WKWebviewViewController dealloc生命周期不触发,存在循环引用问题。 删减代码至不存在该问题,逐步恢复、修改代码排查所有存在循环引用和self未释放的问题
1.  addScriptMessageHandler很容易引起循环引用,导致控制器无法被释放,
    [userCC addScriptMessageHandler:self name:@"ScanAction"];
    所以需要加入以下这段:
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ScanAction"];
2.  在subscribeNext:块中,self获取了文本框的引用,块捕获并保留了范围内的值,因此如果self和此信号之间存在强引用,就会导致循环引用的问题
    function中获取self需要设置为弱引用,当self不再被引用时自动被释放。当时在block里需要是强引用,避免异步情况下值返回时self已经是nil导致应用崩溃
    - (void)bindViewModel {
        __weak __typeof(self) weakSelf = self; // @weakify(self); 
        [[self.viewModel.refreshSubject deliverOnMainThread] subscribeNext:^(id  _Nullable x) {
            __strong __typeof(self) strongSelf = weakSelf;    // @strongify(self);
            [strongSelf disApperClearCache];

        }];
        
3. 在Jsbplun 注册的方法中, 有部分未使用weakify/strongify导致引用未释放
    __weak __typeof(self) weakSelf = self;
    [WKWebViewJavascriptBridge enableLogging];
    // webview建立JS与OjbC的沟通桥梁
    weakSelf.jsBridge = [WKWebViewJavascriptBridge bridgeForWebView:weakSelf.baseWebView];
    // didFinishNavigation生命周期不执行,从而加载框无法隐藏,原因先前这里给的是self.baseWebView,给错传参
    [weakSelf.jsBridge setWebViewDelegate:weakSelf];

NSTimer 循环引用

NSTimer: 经过一定时间间隔后将触发的计时器,会将指定的消息发送到目标对象

@interface TimeViewController ()
@property (nonatomic,weak) NSTimer *timer;
@end
@implementation TimeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建 NSTimer
    NSTimer *aTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
    // 赋值给 weak 变量
    self.timer = aTimer;
    // NSTimer 加入 NSRunLoop
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    if (self.timer == nil) {
        NSLog(@"timer 被释放了");
    }
}

- (void)doSomething {
    NSLog(@"doSomething");
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)dealloc {
    NSLog(@"dealloc");
    // ViewController执行dealloc时timer也销毁
    [self.timer invalidate];
}
循环引用问题:

ViewController并没有执行dealloc方法,所以timer也没有销毁。 NSTimer被释放的前提是ViewController被dealloc,而NSTimer一直强引用着ViewController,这就造成了循环引用
处理办法
只要NSTimer不强引用ViewController,即target对象不是ViewController,就可以解决
加入中间代理对象

@interface TimeViewController ()

@property (nonatomic,strong) NSTimer *timer;

@end

@implementation TimeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 中间代理对象
    self.timer = [NSTimer timerWithTimeInterval:1.0 target:[TAYProxy proxyWithTarget:self] selector:@selector(doSomething) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    
}

- (void)doSomething {
    NSLog(@"doSomething");
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)dealloc {
    NSLog(@"dealloc");
    // ViewController执行dealloc时timer也销毁
    [self.timer invalidate];
}

使用NSProxy类实现消息转发
@interface TestNSProxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (nonatomic, weak) id target;
@end


#import "TestNSProxy.h"
@implementation TestNSProxy
+ (instancetype)proxyWithTarget:(id)target {    
  TestNSProxy *proxy = [TestNSProxy alloc];    
  proxy.target = target;    
  return proxy;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {    
  return [self.target methodSignatureForSelector:sel];
}
- (void)forwardInvocation:(NSInvocation *)invocation {    
  [invocation invokeWithTarget:self.target];
}
@end
改变timer引用
__weak typeof(self) weakSelf = self;   
self.timer = [NSTimer timerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {        
    [weakSelf doSomething];  

使用postMessage交易

// vue相关使用callHandler调用 VueLoaderViewController.m
WKUserScript *commonScript =  [[WKUserScript alloc]
    initWithSource: @"window.WebViewJavascriptBridge = {"
                    "  callHandler: function (name, jsonData, data) {"
                    "    window.webkit.messageHandlers.callHandler.postMessage(JSON.stringify(jsonData));"
                    "  }"
                    "};"
    injectionTime:WKUserScriptInjectionTimeAtDocumentStart
    forMainFrameOnly:YES
    ];
[userCC addUserScript:commonScript];  // 需要在config.userContentController = userCC;赋值后调用

block回调方法


// 定义
@interface VueJSBridgeNative : NSObject

+ (void)callHandler:(NSDictionary *)data completion:(void (^)(NSDictionary *result))completion;

@end

@implementation VueJSBridgeNative

// 实现
+ (void)callHandler:(NSDictionary *)data completion:(void (^)(NSDictionary *result))completion {
    // 在这里执行相应的操作,获取结果 result
    NSDictionary *result = @{ /* 设置结果数据 */ };
    
    // 调用 completion block 传递结果
    if (completion) {
        completion(result);
    }
}

@end

// 调用
[VueJSBridgeNative callHandler:dictData completion:^(NSDictionary *result) {
    // 处理回调结果 result
    if (responseCallback) {
        responseCallback(result);
    }
}];

          
  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值