IOS開發基礎知識--片段15,ios基礎知識--片段

來源:互聯網
上載者:User

IOS開發基礎知識--片段15,ios基礎知識--片段

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;@endHMShop.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 = 0; i<100; i++) {        HMShop *shop = [[HMShop alloc] init];        shop.name = [NSString stringWithFormat:@"商品--%d", i];        shop.price = arc4random() % 10000;                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 = 110;    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時判斷出是哪個自訂按鈕被按下了。建立自訂按鈕,並設為AccessoryViewif (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 = 70;    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 == 2 && indexPath.row == 0) {        cell.accessoryView = [[[UISwitch alloc] init] autorelease];    } else {        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;    }        return cell;}@end

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.