IOS开发基础知识--碎片15
1:将自定义对象转化成NsData存入数据库
要转为nsdata自定义对象要遵循<NSCoding>的协议,然后实现encodeWithCoder,initwithcode对属性转化,实例如下: HMShop.h
#import <Foundation/Foundation.h> @interface HMShop : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) double price;
@end HMShop.m
#import "HMShop.h" @implementation HMShop
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeDouble:self.price forKey:@"price"];
} - (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super init]) {
self.name = [decoder decodeObjectForKey:@"name"];
self.price = [decoder decodeDoubleForKey:@"price"];
}
return self;
} - (NSString *)description
{
return [NSString stringWithFormat:@"%@ <-> %f", self.name, self.price];
}
@end 操作: - (void)addShops
{
NSMutableArray *shops = [NSMutableArray array];
for (int i = ; i<; i++) {
HMShop *shop = [[HMShop alloc] init];
shop.name = [NSString stringWithFormat:@"商品--%d", i];
shop.price = arc4random() % ; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:shop];
[self.db executeUpdateWithFormat:@"INSERT INTO t_shop(shop) VALUES (%@);", data];
}
} - (void)readShops
{
FMResultSet *set = [self.db executeQuery:@"SELECT * FROM t_shop LIMIT 10,10;"];
while (set.next) {
NSData *data = [set objectForColumnName:@"shop"];
HMShop *shop = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"%@", shop);
}
} *把对象转成nsdata的理由,因为在存入数据库时会变成字符串,不利转化,所以先把其序列化转化成nsdata,然后存进数据库,取出时同样先为nsdata再转化;
2:增加子控制器,用来提取一些公共的内容布局,瘦身当前viewcontroller
DetailsViewController *details = [[DetailsViewController alloc] init];
details.photo = self.photo;
details.delegate = self;
[self addChildViewController:details];
CGRect frame = self.view.bounds;
frame.origin.y = ;
details.view.frame = frame;
[self.view addSubview:details.view];
[details didMoveToParentViewController:self];
3:用协议来分离出调用
在子控制器创建一个协议,然后在其内部对它进行处理传参 子控制器.h
@protocol DetailsViewControllerDelegate - (void)didSelectPhotoAttributeWithKey:(NSString *)key; @end @interface DetailsViewController : UITableViewController @property (nonatomic, strong) Photo *photo;
@property (nonatomic, weak) id <DetailsViewControllerDelegate> delegate; @end 子控制器.m - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *key = self.keys[(NSUInteger) indexPath.row];
//对它进行传参,让其在父控制器去实现
[self.delegate didSelectPhotoAttributeWithKey:key];
} 父控制器.m
@interface PhotoViewController () <DetailsViewControllerDelegate>
@end 然后(得到参数,进行原本子控制器要进行的操作):
- (void)didSelectPhotoAttributeWithKey:(NSString *)key
{
DetailViewController *detailViewController = [[DetailViewController alloc] init];
detailViewController.key = key;
[self.navigationController pushViewController:detailViewController animated:YES];
}
4:关于kvo的运用
//进度值改变 增加kvo 传值 key为fractionCompleted
- (void)setProgress:(NSProgress *)progress{
if (_progress) {
[_progress removeObserver:self forKeyPath:@"fractionCompleted"];
}
_progress = progress;
if (_progress) {
[_progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
}
}
//消息kvo消息
- (void)dealloc{
if (_progress) {
[_progress removeObserver:self forKeyPath:@"fractionCompleted"];
}
_progress = nil;
} #pragma mark KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([keyPath isEqualToString:@"fractionCompleted"]) {
NSProgress *progress = (NSProgress *)object;
NSProgress *cellProgress = _offsourecebean.cDownloadTask.progress;
BOOL belongSelf = NO;
if (cellProgress && cellProgress == progress) {
belongSelf = YES;
}
dispatch_async(dispatch_get_main_queue(), ^{
if (self) {
[self showProgress:progress belongSelf:belongSelf];
}
});
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
} *注意增加监听后在不用时要进行消除,移除观察,其中addObserver可以是其它对象,然后在其内部实现observeValueForKeyPath这个协议;增加监听时可以设置options类型,也可以多类型一起;比如NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld;当被监听的对象发生变化时,会马上通知监听对象,使它可以做出一些响应,比如视图的更新;
5:自定义UITableViewCell的accessoryView 判断哪个Button按下
UITableview的开发中经常要自定义Cell右侧的AccessoryView,把他换成带图片的按钮,并在用户Tap时判断出是哪个自定义按钮被按下了。 创建自定义按钮,并设为AccessoryView
if (cell == nil) {
cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; UIImage *image= [ UIImage imageNamed:@"delete.png" ];
UIButton *button = [ UIButton buttonWithType:UIButtonTypeCustom ];
CGRect frame = CGRectMake( 0.0 , 0.0 , image.size.width , image.size.height );
button. frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal ];
button. backgroundColor = [UIColor clearColor ];
[button addTarget:self action:@selector(buttonPressedAction forControlEvents:UIControlEventTouchUpInside];
cell. accessoryView = button;
} 如果将Button加入到cell.contentView中,也是可以的。
cell.contentView addSubview:button]; 在Tap时进行判断,得到用户Tap的Cell的IndexPath
- (void)buttonPressedAction id)sender
{
UIButton *button = (UIButton *)sender;
(UITableViewCell*)cell = [button superview];
int row = [myTable indexPathForCell:cell].row;
} 对于加到contentview里的Button
(UITableViewCell*)cell = [[button superview] superview];
6:直接运用系统自带的UITableViewCell,其中cell.accessoryView可以自定义控件
#import "MyselfViewController.h" @interface MyselfViewController () @property (nonatomic, retain) NSMutableArray *datasource; @end @implementation MyselfViewController
-(void)dealloc {
[_datasource release];
[super dealloc];
} -(NSMutableArray *)datasource {
if (!_datasource) {
self.datasource = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"MyselfList" ofType:@"plist"]];
}
return _datasource;
} -(instancetype)init {
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) { }
return self;
} - (void)viewDidLoad {
[super viewDidLoad]; [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
self.tableView.rowHeight = ;
self.navigationItem.title = @"我的";
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.datasource.count;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section.
return [self.datasource[section] count];
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
NSDictionary *dict = [self.datasource[indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.text = dict[@"title"];
cell.imageView.image = [UIImage imageNamed:dict[@"imageName"]]; if (indexPath.section == && indexPath.row == ) {
cell.accessoryView = [[[UISwitch alloc] init] autorelease];
} else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} return cell;
} @end
IOS开发基础知识--碎片15的更多相关文章
- IOS开发基础知识碎片-导航
		
1:IOS开发基础知识--碎片1 a:NSString与NSInteger的互换 b:Objective-c中集合里面不能存放基础类型,比如int string float等,只能把它们转化成对象才可 ...
 - IOS开发基础知识--碎片19
		
1:键盘事件顺序 UIKeyboardWillShowNotification // 键盘显示之前 UIKeyboardDidShowNotification // 键盘显示完成后 UIKeyboar ...
 - IOS开发基础知识--碎片33
		
1:AFNetworking状态栏网络请求效果 直接在AppDelegate里面didFinishLaunchingWithOptions进行设置 [[AFNetworkActivityIndicat ...
 - IOS开发基础知识--碎片40
		
1:Masonry快速查看报错小技巧 self.statusLabel = [UILabel new]; [self.contentView addSubview:self.statusLabel]; ...
 - IOS开发基础知识--碎片42
		
1:报thread 1:exc_bad_access(code=1,address=0x70********) 闪退 这种错误通常是内存管理的问题,一般是访问了已经释放的对象导致的,可以开启僵尸对象( ...
 - IOS开发基础知识--碎片50
		
1:Masonry 2个或2个以上的控件等间隔排序 /** * 多个控件固定间隔的等间隔排列,变化的是控件的长度或者宽度值 * * @param axisType 轴线方向 * @param fi ...
 - IOS开发基础知识--碎片3
		
十二:判断设备 //设备名称 return [UIDevice currentDevice].name; //设备型号,只可得到是何设备,无法得到是第几代设备 return [UIDevice cur ...
 - IOS开发基础知识--碎片11
		
1:AFNetwork判断网络状态 #import “AFNetworkActivityIndicatorManager.h" - (BOOL)application:(UIApplicat ...
 - IOS开发基础知识--碎片14
		
1:ZIP文件压缩跟解压,使用ZipArchive 创建/添加一个zip包 ZipArchive* zipFile = [[ZipArchive alloc] init]; //次数得zipfilen ...
 
随机推荐
- Neutron 网络基本概念 - 每天5分钟玩转 OpenStack(66)
			
上次我们讨论了 Neutron 提供的功能,今天我们学习 Neutron 模块几个重要的概念. Neutron 管理的网络资源包括 Network,subnet 和 port,下面依次介绍. netw ...
 - jQuery架构剖析
			
对于jQuery的整体架构,经典之处有三: 1.jQuery的无new构建 2.jQuery的链式调用 3.jQuery的插件接口 想必兄弟姐妹们也觉得这架构不错哈,但有时又畏惧去拜读大量的jQuer ...
 - EF7 Code First Only-所引发的一些“臆想”
			
At TechEd North America we were excited to announce our plans for EF7, and even demo some very early ...
 - 【记录】VS2012新建MVC3/MVC4项目时,报:此模板尝试加载组件程序集“NuGet.VisualStudio.Interop...”
			
最近电脑装了 VisualStudio "14" CTP,由于把其他版本的 VS 卸掉,由高到低版本安装,当时安装完 VisualStudio "14" CTP ...
 - C++ 与 php 的交互 之----- C++ 获取 网页文字内容,获取 php 的 echo 值。
			
转载请声明出处! http://www.cnblogs.com/linguanh/category/633252.html 距离上次 谈 C++ 制作json 或者其他数据传送给 服务器,时隔两个多月 ...
 - 《selenium2 Java 自动化测试实战(第二版)》 更新2016.5.3
			
java 版来了!! 本文档在<selenium2 Python 自动化测试实战>的基础上,将代码与实例替换为java ,当然,部分章节有变更.这主要更语言本身的特点有关.集合和java下 ...
 - Sql Server函数全解(四)日期和时间函数
			
日期和时间函数主要用来处理日期和时间值,本篇主要介绍各种日期和时间函数的功能和用法,一般的日期函数除了使用date类型的参数外,也可以使用datetime类型的参数,但会忽略这些值的时间部分.相同 ...
 - SpringData —— HelloWorld
			
SpringData 简介 优点 简化数据库访问,减少数据访问层的开发量. 支持的数据库类型 支持 NoSQL 存储,如 MongoDB,Redis. 支持关系型数据存储技术,如 jdbc,jpa. ...
 - cookie设置保存用户名,填入中文名之后出现的错误500问题
			
对于问题发生的原因以后再来补充: 解决方法就是在dologin.jsp当中使用URLEncode工具类,这个工具类在java的net包当中 <一>用户浏览器-->jsp 的过程 1 ...
 - C# Enum Name String Description之间的相互转换
			
最近工作中经常用到Enum中Value.String.Description之间的相互转换,特此总结一下. 1.首先定义Enum对象 public enum Weekday { [Descriptio ...