CardView使用与兼容

1.5.0版本:

%title插图%num

2.细节:margin与阴影(5.0+)

4.4因为阴影比较大,所以需要设置android:layout_margin=”0dp”,减小阴影

%title插图%num

3.按压下沉,阴影加重效果:

5.0以上才有

4.4需要自己自定义

1 android:stateListAnimator="@drawable/z_translation"

%title插图%num

4.关于app:contentPadding:

5.0上面需要设置这个,不然里面TextView会贴到圆角上

%title插图%num

图1

%title插图%num

图2

%title插图%num

图3

4.4上面不需要设置这个

5.关于app:cardCornerRadius边框圆角:

5.0+ 图片和布局都可以很好的呈现圆角效果,图片也变圆角了

%title插图%num

4.x 图不能变成圆角,如果要做成5.x一样的效果:通过加载图片的时候自己去处理成圆角

 

6.关于app:cardElevation:

app:cardElevation=”10dp” 阴影效果 (值越大阴影效果越明显)

 

7.5.0效果图:

%title插图%num

 

快速讲解CardView的使用

CardView和RecyclerView一样是Android5.0以后新出现的控件,伴随着Material Design设计而诞生。

一、引入CardView

在AS新建项目中需要使用CardView组件,和RecyclerView一样,需要在Gradle里面提前加入CardView的

包,直接在Gradle中加入:

compile ‘com.android.support:cardview-v7:25.3.1’(CardView版本号与项目里面V7版本号相同即可)

或者在Library dependence中输入CardView,选择V7包下那个即可。

二、为何使用CardView

CardView是继承自FramLayout的一个布局控件,官网里对CardView的注释为:

A FrameLayout with a rounded corner background and shadow.(CardView为带圆角和阴影的FramLayout)

以往,我们需要自定义Shape来实现圆角和阴影效果;现在,这些效果集成到了CardView的属性里。同时,

CardView应该被使用在显示层次性的内容时,在显示列表或网格时更应该被选择,因为这些边缘可以使得用户

更容易去区分这些内容。

三、CardView属性

app:cardBackgroundColor      设置背景颜色

app:cardCornerRadius         设置圆角大小

app:cardElevation            设置z轴阴影高度

app:cardMaxElevation         设置z轴*大高度值

app:contentPadding           内容与边距的间隔

app:contentPaddingLeft       内容与左边的间隔

app:contentPaddingTop        内容与顶部的间隔

app:contentPaddingRight      内容与右边的间隔

app:contentPaddingBottom     内容与底部的间隔

app:paddingStart             内容与边距的间隔起始

app:paddingEnd               内容与边距的间隔终止

app:cardUseCompatPadding     设置内边距,在API21及以上版本和之前的版本仍旧具有一样的计算方式

app:cardPreventConrerOverlap 在API20及以下版本中添加内边距,这个属性为了防止内容和边角的重叠

注意:CardView中使用android:background设置背景颜色无效。

Ps:多说一句,有时候部分人为了突出这些属性是在CardView中使用的,会在CardView内重新命名属性名,

如:xmlns:card_view=”http://schemas.android.com/apk/res-auto”,那么app就会变成card_view,但是

直接使用app不影响什么,只是一个属性前缀名的变化。

四、点击CardView出现波纹(Ripple)效果

在CardView布局中加入:android:foreground=”?android:attr/selectableItemBackground”即可实现

点击CardView出现波纹效果。

 

友情链接:

CardView更多使用细节

http://www.open-open.com/lib/view/open1476847497671.html
————————————————

升级 AndroidX 之后 常用的依赖

1、CardView
implementation ‘androidx.cardview:cardview:1.0.0’

2、TabLayout
implementation ‘com.google.android.material:material:1.0.0’

3、RecycleView
implementation ‘androidx.recyclerview:recyclerview:1.0.0’

4、Snackbar
implementation ‘com.google.android.material.snackbar.Snackbar:1.0.0-rc01’

5、swiperefreshlayout
implementation ‘androidx.swiperefreshlayout:swiperefreshlayout:1.0.0’

6、viewpager
implementation ‘androidx.viewpager:viewpager:1.0.0’

7、design ui 库
implementation ‘com.google.android.material:material:1.0.0-rc01’

8、coordinatorlayout
implementation ‘androidx.coordinatorlayout:coordinatorlayout:1.0.0’

9、constraintlayout 约束布局
implementation ‘androidx.constraintlayout:constraintlayout:1.1.2’

10、NavigationView 侧滑
implementation ‘com.google.android.material.navigation.NavigationView:1.0.0′

11、drawerlayout 抽屉布局
implementation’androidx.drawerlayout:drawerlayout:1.0.0′

12、gridlayout 网格布局
implementation’androidx.gridlayout:gridlayout:1.0.0′

13、recyclerview-selection RecycleView 高亮显示方案
implementation’androidx.recyclerview:recyclerview-selection:1.0.0’

14、附赠 国内可打开的 官方对照连接
AndroidX 依赖对比 google官方

15、viewPager 2 这个是2与viewPager不同哦
implementation ‘androidx.viewpager2:viewpager2:1.0.0’
————————————————

GitHub上完整的iOS-App源码

1. Coding iOS 客户端
Coding官方客户端. 强烈推荐的值得学习的完整APP.
GitHub – Coding/Coding-iOS: Coding iOS 客户端源代码

2. OSCHINA 的 iPhone 客户端
开源中国的iPhone客户端源码
https://git.oschina.net/oschina/iphone-app

3. Git@OSC

Git@OSC iPhone 客户端,方便用户查看Git@OSC的项目以及简单的操作issue等
oschina / git-osc-iphone

4. Firefox for iOS

GitHub – mozilla/firefox-ios: Firefox for iOS

5. zulip-ios
Dropbox收购公司内部社交服务商Zulip,然后全部开源,这是iOS App
GitHub – zulip/zulip-ios: Zulip iOS app

6. iOSSF
SegmentFault官方App
GitHub – gaosboy/iOSSF: SegmentFault官方App

7. iReddit
Reddit iPhone客户端
GitHub – reddit/iReddit: The iReddit iPhone app

8. Monkey
GitHub第三方iOS客户端
GitHub – coderyi/Monkey: Monkey is a GitHub third party client for iOS,to show the rank of coders and repositories.

9. Watch
Dribbble第三方客户端
GitHub – tuesda/Watch: A project which demonstrate how to develop a custom client on android for dribbble.com

10. Voice2Note
懒人笔记iOS客户端
GitHub – liaojinxing/Voice2Note: 懒人笔记iOS客户端

11. RSSRead
“已阅”(iOS上开源RSS新闻阅读器)
GitHub – ming1016/RSSRead: “已阅”(iOS上开源RSS新闻阅读器),有兴趣?那就Pull Requests吧

12. BeeFancy
BeeFancy仿Fancy官方APP的WIREFRAME,基于BeeFramework
GitHub – BeeFramework/BeeFancy: 仿Fancy官方APP的WIREFRAME,基于BeeFramework

13. SXNews
模仿网易新闻做的精仿网易新闻
GitHub – dsxNiubility/SXNews: High imitation Neteasy News. (include list,detail,photoset,weather,feedback)

14. Doppio
寻找*近的星巴克
GitHub – chroman/Doppio: An open source iOS app to find the nearest Starbucks store using NSURLSession, AFNetworking 2.0, Mantle and Starbucks private API.

15. Anypic
类似于Instagram的一款App
GitHub – ParsePlatform/Anypic: An open source mobile and web app that lets users share photos similar to Instagram

16. 豆瓣相册
Slowslab iOS应用 豆瓣相册 精选集 开源项目
GitHub – TonnyTao/DoubanAlbum: Slowslab iOS应用 豆瓣相册 精选集 开源项目,仅供学习参考

17. ChatSecure-iOS
Objective-C写的XMPP聊天应用
GitHub – ChatSecure/ChatSecure-iOS: ChatSecure is a free and open source encrypted chat client for iPhone and Android that supports OTR encryption over XMPP.

18. NotificationChat
Objective-C写的完整的聊天应用
GitHub – relatedcode/EncryptedChat: This is a full native iPhone app to create realtime, text based group or private chat with Parse and Firebase.

19. FakeZhihuDaily
仿知乎日报iOS客户端
GitHub – gnou/FakeZhihuDaily: 仿知乎日报iOS客户端

20. ruby-china-for-ios
RubyChina官方客户端
GitHub – ruby-china/ruby-china-for-ios: Ruby China client for iOS

21. Meizi
豆瓣妹子图iOS客户端
GitHub – Sunnyyoung/Meizi: 豆瓣妹子图iOS客户端

22. PlainReader
一款 iOS(iPhone + iPad) 新闻类客户端,内容抓取自 http://cnBeta.com
PlainReader/PlainReader at master · guojiubo/PlainReader · GitHub

23. iOS-2048
用Objective-C实现的2048游戏
GitHub – austinzheng/iOS-2048: iOS drop-in library presenting a 2048-style game

24. ECMobile_iOS
基于ECShop的手机商城客户端
GitHub – GeekZooStudio/ECMobile_iOS: 基于ECShop的手机商城客户端

25. wikipedia-ios
维基百科官方App, 已上架
GitHub – wikimedia/wikipedia-ios: The official Wikipedia iOS app.

26. Sol
漂亮的扁平风格的天气App
GitHub – comyarzaheri/Sol: Sol° beautifully displays weather information so you can plan your day accordingly. Check the weather in your current location or any city around the world. Implemented in Objective-C.

27. v2ex
v2ex第三方iOS客户端
v2ex/v2ex-iOS at master · singro/v2ex · GitHub

28. MyOne-iOS
用OC写的《一个》 iOS 客户端
GitHub – meilbn/MyOne-iOS: 我的《一个》 iOS 客户端(OC)

29. WNXHuntForCity
高仿城觅2.0 by-objective-c
GitHub – ZhongTaoTian/WNXHuntForCity: 高仿城觅by-objective-c

30. viewfinder
移动支付公司 Square 将去年收购的照片应用 Viewfinder 开源了,包含服务端、iOS 和 Android 应用代码
GitHub – viewfinderco/viewfinder: Viewfinder client and server code

31. breadwallet
breadwallet iOS bitcoin wallet
GitHub – voisine/breadwallet: breadwallet

32. novel-design
品趣iOS客户端
GitHub – ltebean/novel-design: PinQu ios client

33. WWDC-2014
WWDC客户端
GitHub – indragiek/WWDC-2014: Scholarship submission for WWDC 2014

34. GreatReader
GreatReader PDF阅读客户端
GitHub – semweb/GreatReader: A “great” PDF reader for iOS. Available on the App Store.

35. Tropos
天气客户端
GitHub – thoughtbot/Tropos: Weather and Forecasts for Humans

36. manong-reading
《猿已阅》码农周刊iOS客户端
GitHub – icepy/manong-reading: 《猿已阅》码农周刊iOS客户端

37. YoCelsius
一款天气预报的应用
GitHub – YouXianMing/YoCelsius: 一款天气预报的应用(已在AppStore上线)

38. 密记iOS版
本应用主要功能是简单笔记
GitHub – iHTCboy/SecurityNote: 密记iOS版,*个开发的完整iOS应用,本应用主要功能是简单笔记。The application of the main function is a simple notes.

39. phphub-ios

PHPHub for iOS is the universal iPhone and iPad application for PHPHub PHPHub – PHP & Laravel的中文社区
GitHub – Aufree/phphub-ios: PHPHub for iOS is the universal iPhone and iPad application for PHPHub

40. Brushes

绘图应用. Painting app for the iPhone and iPad.
GitHub – sprang/Brushes: Painting app for the iPhone and iPad.

41. Inkpad
绘图应用. Inkpad is a vector illustration app designed from scratch for the iPad.
GitHub – sprang/Inkpad: Vector illustration app for the iPad.

42. wh-app-ios

美国白宫(WhiteHouse)的官方app.
GitHub – WhiteHouse/wh-app-ios

43. cheddar-ios
一款日程管理软件.
GitHub – nothingmagical/cheddar-ios: Cheddar for iOS

44. newsyc
Hacker News的iPhone客户端
GitHub – Xuzz/newsyc: An iPhone Hacker News client.

45. WordPress for iOS

WordPress iOS官方客户端. 笔者强烈推荐的开源项目.
GitHub – wordpress-mobile/WordPress-iOS: WordPress for iOS

46. WikiHow
Wikihow–WikiHow的官方app.
GitHub – tderouin/wikiHow-iPhone-Application: The code for the wikihow’s iphone app

47. Dollar Bets
记录你和朋友打赌的内容.
GitHub – Rich86man/Dollar-Bets: An iPhone app to keep track of your Dollar Bets

48. Dozuki
iFixit网站的互动修理手册
GitHub – iFixit/iFixit-iOS: iFixit’s iOS app for iPad, iPhone, and iPod touch

49. Last.fm
Last.fm 的客户端,国外很火的私人电台.
GitHub – lastfm/lastfm-iphone: The official Last.fm iPhone application

50. ioctocat
GitHub第三方客户端.
GitHub – dennisreimann/ioctocat: iOctocat v1

51. iTunesPicker
类似AppStore的一个应用
GitHub – appcornerit/iTunesPicker: Discover, search and compare world rankings for apps, ibooks, movies, music videos and music from iTunes (and AppStore) in any available country.

52. TeamTalk
蘑菇街TeamTalk. 开源IM. 笔者强烈推荐.
GitHub – mogujie/TeamTalk: TeamTalk is a solution for enterprise IM

53. shadowsocks-iOS

*工具Shadowsocks. Github目前代码已经被移除, 不过2.6.3的还是保留着.

GitHub – shadowsocks/shadowsocks-iOS at 2.6.3: Removed according to regulations.

54. MessageDisplayKit
一个类似微信App的IM应用,拥有发送文字、图片、语音、视频、地理位置消息,管理本地通信录、分享朋友 圈、漂流交友、摇一摇和更多有趣的功能。笔者推荐的学习IM的好东西.
GitHub – xhzengAIB/MessageDisplayKit: An IM App like WeChat App has to send text, pictures, audio, video, location messaging, managing local address book, share a circle of friends, drifting friends, shake a fun and more interesting features.

55. NewsBlur
个人新闻阅读器.
NewsBlur/clients/ios at master · samuelclay/NewsBlur · GitHub

56. VLC for iOS
VLC媒体播放器. 官方页面提供源代码下载.
http://www.videolan.org/vlc/download-ios.html

57. Frameless – 全屏Web浏览器
GitHub – stakes/Frameless: A chromeless web browser for viewing prototypes.

58. Koala Hates Rain – iOS游戏

[开源APP推荐] Koala Hates Rain

59. OctoPodium

列出用户排名基于Github代码库的Star数量.
[开源APP推荐] OctoPodium

iOS钥匙串

iOS本地化存储信息
本地化不能存储明文,如果采用MD5 加密,因为MD5加密后都是64位的,过于复杂.所以本地采用钥匙串才是*明智的选择.
钥匙串是iOS7.0.3版本推出来的功能.(iCloud钥匙串),采用256位AES加密技术,用户的信息非常安全.
// 获取应用程序唯一标识.(一般我们都将程序的唯一标识作为钥匙串的Service的值)
// NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
//存放信息
BOOL isStoreSuccess = [SSKeychain setPassword:@”myPassword” forService:@”kLoginKeyServiceName” account:@”Rephontil”];
//读取信息
NSString *password = [SSKeychain passwordForService:@”kLoginKeyServiceName” account:@”Rephontil”];
//log
NSLog(@”isStoreSuccess = %d, %@ %@”, isStoreSuccess,[SSKeychain allAccounts],password);
//删除对应的账户信息
//[SSKeychain deletePasswordForService:@”kLoginKeyServiceName” account:@”Rephontil”];
NSLog(@”isStoreSuccess = %d, %@ %@”, isStoreSuccess,[SSKeychain allAccounts],password);

使用钥匙串注意
温馨提示:使用钥匙串记得先在Capabilities里面打开Keychain Sharing的开关哦

 

iOS指纹登录

指纹登录简述
#pragma mark 指纹识别
//指纹识别功能是 iphone 5S之后推出的.SDK是 iOS 8.0 推出!
//推出指纹识别功能的目的,是为了简化移动支付环节,占领移动支付市场.
– (void)fingerPrintIdentification
{
// 1️⃣获得当前系统版本号
float version = [UIDevice currentDevice].systemVersion.floatValue;

if (version < 8.0 ) // 判断当前系统版本
{
NSLog(@”系统版本太低,请升级至*新系统”);
return;
}
// 2️⃣ 实例化指纹识别对象,判断当前设备是否支持指纹识别功能(是否带有TouchID)

// 1> 实例化指纹识别对象
LAContext *laCtx = [[LAContext alloc] init];

// 2> 判断当前设备是否支持指纹识别功能.
if (![laCtx canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:NULL]) {

// 如果设备不支持指纹识别功能
NSLog(@”该设备不支持指纹识别功能”);

return;
};

[laCtx evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@”指纹登陆” reply:^(BOOL success, NSError *error) {
// 如果成功,表示指纹输入正确.
if (success) {
NSLog(@”指纹识别成功!”);

} else {
NSLog(@”指纹识别错误,请再次尝试”);
}
}];

}

%title插图%num

 

iOS新项目的环境配置info.plist文件

iOS新项目的环境配置info.plist文件

Bundle ID有什么用? —–>用于产品上线,推送注册等。苹果根据Bundle ID找到手机上的这种应用,然后将后台消息推送给用户。
Bundle ID格式:类似于这样 com.tencent.wechat  (com.公司名.应用名)

上传的时候版本号不能相等,并且版本号必须要比之前的版本号大!(Version是应用在APP store里面展示的版本号,build是内部的打包测试的号,每一次打包,build号都需要自增,但是Version只有发布到App store成功以后,下次再发布才必须自增)

Development Target支持的iOS系统版本。

Main Interface(程序启动自动加载Main storeboard)

main.m文件里面的main函数所做的事情为以下4步:
1.创建一个UIApplication对象
2.创建UIApplication代理对象,并且成为UIApplication对象代理属性
3.开启主运行循环,保证程序一直跑起来,不立即结束(检测用户的触摸事件)
4加载info.plist文件,判断info.plist文件里面有没有执行main.stroeboard,如果指定就会加载main storeboard.

Main Interface指定程序启动的主窗口,默认指向scoreboard创建的主窗口,一般应用都是纯代码搭建主界面,这里Main Interface设置为空。

Device Oriention为设备支持的旋转方向。

status bar style :为状态栏的样式(即电源栏的样式高亮、默认,是否显示、隐藏)。

点击tabBar切换自控制器的原理:把上一个控制器view移除,然后把当前控制器view添加上去。
创建窗口,设置窗口的跟控制器,然后设置为主窗口。

App icon  项目图标。pt为点的单位,例如icon为29pt的图片,@2x的icon转换为像素就是 29*2 = 58个像素。
icon里面多余的图片都是在下面的unsigned上面,这些图片可以直接删掉,程序打包的时候不会打包这些没有使用的Appicon。

LaunchScreen:代理之前的启动图片。程序中碰到模拟器尺寸不对,马上找启动图片,默认模拟器的尺寸由启动图片决定。
LaunchScreen的好处:1可以展示更多的东西。  2 可以只求美工出一个大尺寸的图片。
启动图片的优先级Launch Images Sources:启动图片的优先级 < Launch Screen File,所以一般需要将后者设为空。

让iOS程序一直在后台运行

1 众所周知,iOS程序退入后台以后一段时间就会被杀死。那么如何保证一个应用程序进入后台以后一直保持活跃呢??通常*常见的方法就是在后台播放一段音频(没有声音),因为AVPlayer这个类进入后台以后可以保证程序不死。

首先我们需要在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法里面实现下面几段代码:

// 设置音频会话
AVAudioSession *session = [AVAudioSession sharedInstance];

// 后台播放
[session setCategory:AVAudioSessionCategoryPlayback error:nil];

// 单独播放一个后台程序
[session setCategory:AVAudioSessionCategorySoloAmbient error:nil];

[session setActive:YES error:nil];

2 在程序进入后台时,开启一个后台任务,时间不确定,这个优先级比较低,如果系统内存不足需要关闭应用的时候,系统首先会考虑关闭这个应用,但是总比不开启后台任务要好。

// 程序进入后台的时候调用
– (void)applicationDidEnterBackground:(UIApplication *)application {

// 开启一个后台任务,时间不确定,优先级比较低,假如系统要关闭应用,首先就考虑
UIBackgroundTaskIdentifier ID = [application beginBackgroundTaskWithExpirationHandler:^{

// 当后台任务结束的时候调用
[application endBackgroundTask:ID];

}];

// 如何提高后台任务的优先级,欺骗苹果,我们是后台播放程序

// 但是苹果会检测你的程序当时有没有播放音乐,如果没有,有可能就干掉你

// 微博:在程序即将失去焦点的时候播放静音音乐.

}

3 在程序即将不活跃的时候循环播放一段音频,是应用一直不被杀死。

// 失去焦点
– (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
NSURL *url = [[NSBundle mainBundle] URLForResource:@”silence.mp3″ withExtension:nil];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[player prepareToPlay];
// 无限播放
player.numberOfLoops = -1;

[player play];

_player = player;
}

4.设置后台的模式

通过上面的4步骤就可以实现应用程序一直在后台运行了。

iOS 数据请求之网络层和数据层

在移动端开发中免不了要发送网络请求数据,一直以来我都没有数据层这个概念,偶然一次机会看网络视频,从一位叫MJ的大神那里获得“数据层”这个概念,在网络请求之后进行数据解析的时候尝试了下,发现层次感非常强��,代码的可读性很高,因此Mark一下。与君共勉!

下面将展示一个*常见的开发中例子:请求*新的列表数据。方法一非常常见:通常我们在请求的这个方法里面会进行参数赋值、字典数组与模型数组的转换等,使得请求的方法里面代码量很大,可读性差。

而!方法二是采用数据层的思想,已经将网络请求与数据处理彻底分开。因为在控制器里面只需要后的*新的数据,而不管请求这个过程,所以将网络请求这部分代码单独地抽取出来在一个工具类里面实现,抽取后的方法只需要我们提供请求所需要的动态参数,然后通过block将我们所需要的数据传递过来,代码的可读性强。推荐使用。
*#pragma mark –获取*新的数据(方法一 传统方法)*
– (void)getNewData
{
NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
paraDic[@”access_token”] = [ZYAccountTool account].access_token;

if (self.status.count) {
paraDic[@”since_id”] = [self.status.firstObject idstr];
}
[ZYHttpTool get:@”https://api.weibo.com/2/statuses/friends_timeline.json” parameters:paraDic progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
ZYLog(@”ZYHttpTool –>%@”,responseObject);

[self.tableView.mj_header endRefreshing];

// 字典数组
NSArray *dataArr = responseObject[@”statuses”];

NSArray *status = [ZYStatus mj_objectArrayWithKeyValuesArray:dataArr];

[self.status addObjectsFromArray:status];
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, status.count)];

// NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:status.count];
[self.status insertObjects:status atIndexes:indexSet];

[self.tableView reloadData];

} failure:^(NSURLSessionDataTask *task, NSError *error) {

}];

}

***#pragma mark –获取*新的数据(方法二 采用数据层思想的方法)***
– (void)otherMethodNewStatus
{
NSString *sinceId = nil;
if (self.status.count) {

sinceId = [self.status.firstObject idstr];

}
[ZYStatusTool newStatusWithSinceId:sinceId success:^(NSArray *modelArray) {

[self.tableView.mj_header endRefreshing];

NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, modelArray.count)];
[self.status insertObjects:modelArray atIndexes:indexSet];

[self.tableView reloadData];

} failure:^(NSError *error) {
ZYLog(@”失败了”);

}];
}

由上面两段代码明显看出:方法二目的性强,可读性高!简洁明了。

下面再看看数据层的代码封装方法:

/**
* 请求更新的微博数据
sinceId:返回比这个更大的微博数据
success:请求成功的时候回调(statuses(ZYStatus模型))
failure:请求失败的时候回调,错误传递给外界

*/
+ (void)newStatusWithSinceId:(NSString *)sinceId
success:(void(^)(NSArray *modelArray))success
failure:(void(^)(NSError *error))failure
{
ZYStatusPara *para = [ZYStatusPara sharedManager];
para.access_token = [ZYAccountTool account].access_token;

if (sinceId) {
para.since_id = sinceId;
}

[ZYHttpTool get:@”https://api.weibo.com/2/statuses/friends_timeline.json” parameters:para.mj_keyValues progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {

NSArray *dicArray = responseObject[@”statuses”];

NSArray *modelArray = [ZYStatus mj_objectArrayWithKeyValuesArray:dicArray];

//只要请求成功了,就通过上面两步对返回的数据responseObject进行处理得到模型数组,然后将模型数组作为参数传递出去给外界使用!!
if (success) {
success(modelArray);
}

} failure:^(NSURLSessionDataTask *task, NSError *error) {

if (failure) {
failure(error);
}
}];

}

//数据层,我们将那些固定的参数都在这里处理完毕,只提供那些动态的参数字段供调用的时候赋值。

下面再看看对网络层的封装:网络层直接通过第第三方开源库AFNetWorking进行二次封装,这样以后整个工程改动的地方小,减少对AFNetWorking的依赖。

/**
GET请求方式

@param URLString 请求的主URL
@param parameters 请求参数
@param progress 进度
@param success 成功的回调
@param failure 失败的回调
*/
+ (void)get:(NSString *)URLString
parameters:(id)parameters
progress:(void(^)(NSProgress *downloadProgress))progress
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
// 获取http请求管理者
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

[mgr GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
if (progress) {
progress(downloadProgress);
}

} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(task,responseObject);
}

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(task, error);
}

}];

}

1. 两数之和(JS实现)

1. 两数之和(JS实现)
1 题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
2 思路
运用hashmap进行查找,节约时间
3代码
var twoSum = function(nums, target) {
    var map = {};
    for (var i=0;i<nums.length;i++) {
        if (typeof map[target – nums[i]] !== ‘undefined’) {
            return [map[target – nums[i]], i];
        } else {
            map[nums[i]] = i;
        }
    }
};