ios 项目总结二

项目基本上完成:总结下:

  代码写的比较乱,许多东西的代码全部写在了一个类了,导致一个类的代码行数超过千行,,发现写的时候容易,到后面再看的,维护的话出很麻烦, 所以以后最近写成工具类,多思考,这样代码才会整洁,有效,效率高,还有就是写代码前,要多思考,比没有目的的写代码强百倍,多思考,才会进步的更快,下面就是项目中常用的demo。

  1   [application setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];//去掉导航

 2 运用了UIviewcontrol添加子的 UIviewcontrol的类的方法实现:实现方法就是定义个父的UIViewController,然后添加子的UIViewController,添加的方式就是:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 60, 1024, 768-60)];
    [contentView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:contentView];
    
    chanPinVC=[[ChanPinTuiJian_ViewController alloc]init];
    [self addChildViewController:chanPinVC];
    
    liuXingVC =[[LiuXing_ViewController alloc]init];
    [self addChildViewController:liuXingVC];
    
    guanZhuVC=[[GuanZhu_ViewController alloc]init];
    [self addChildViewController:guanZhuVC];
    
    vipVC=[[Vip_ViewController alloc]init];
    [self addChildViewController:vipVC];
    
    [contentView addSubview:chanPinVC.view];
    currentViewController=chanPinVC;

}

页面的跳转是在父的viewController里面进行的,

//页面跳转button点击事件
-(void)click:(UIButton *)sender{
    //移除掉添加在产品页面的单品View;
if (sender.tag==3) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"dataOne" object:nil];

    }
    if ((currentViewController == chanPinVC && sender.tag == 1)||(currentViewController == liuXingVC && sender.tag == 2)||(currentViewController == guanZhuVC && sender.tag == 3)||(currentViewController == vipVC && sender.tag == 4)) {
        return;//此方法判断是防止重复点击
    }
    
    UIViewController *oldViewController=currentViewController;
    switch (sender.tag) {
        case 1:{
            //产品推荐 页面跳转的方法用的是transitionWithView 
            [UIView transitionWithView:self.view duration:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
                imagejiao.frame=CGRectMake(152, 58-8, 19, 8);
            }completion:NULL];

            [self transitionFromViewController:currentViewController toViewController:chanPinVC duration:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
            }  completion:^(BOOL finished) {
                if (finished) {
                    currentViewController=chanPinVC;
                }else{
                    currentViewController=oldViewController;
                }
            }];
            
        }
            
            break;
        case 2:{
             //流行趋势
            [UIView transitionWithView:self.view duration:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
                imagejiao.frame=CGRectMake(204+32, 58-8, 19, 8);
            }completion:NULL];

            [self transitionFromViewController:currentViewController toViewController:liuXingVC duration:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
            }  completion:^(BOOL finished) {
                if (finished) {
                    currentViewController=liuXingVC;
                }else{
                    currentViewController=oldViewController;
                }
            }];
        }
            
            break;
        case 3:{
             //产品关注
            [UIView transitionWithView:self.view duration:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
                imagejiao.frame=CGRectMake(290+32, 58-8, 19, 8);
            }completion:NULL];
            [self transitionFromViewController:currentViewController toViewController:guanZhuVC duration:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{} completion:^(BOOL finished){
                if (finished) {
                    currentViewController=guanZhuVC;
                }else{
                    currentViewController=oldViewController;
                }
            }];
            
        }
            
            break;
        case 4:{
             //vip服务
            [UIView transitionWithView:self.view duration:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
                imagejiao.frame=CGRectMake(376+32, 58-8, 19, 8);
            }completion:NULL];
            [self transitionFromViewController:currentViewController toViewController:vipVC duration:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{} completion:^(BOOL finished){
                if (finished) {
                    currentViewController=vipVC;
                }else{
                    currentViewController=oldViewController;
                }
            }];
            
            
        } break;
        default:
            break;
    }
    
}

3 一个页面的多个tableview的实现:tableview的判断方法是根据tableview==的方法,判断,还有就是重绘tableview的时候,里面的数据源显示的时候有时会出现混乱,所以解决的方法就是把tableview的数据在cell方法中,写在if(cell==nil){}的外面,还有就是一个        NSString *identity=[NSString stringWithFormat:@"%d%d",indexPath.section,indexPath.row];这样写,
4 扫描二维码的实现:添加 libiconv.dylib库,还有就是ZBarSDK库,调用的方法:

//二维码显示
-(void)saoMiao{
    
    ZBarReaderViewController *reader = [ZBarReaderViewController new];
    reader.readerDelegate = self;
//   reader.readerView.torchMode = 1;
    ZBarImageScanner *scanner = reader.scanner;
    reader.supportedOrientationsMask = UIInterfaceOrientationPortrait;
    [scanner setSymbology: ZBAR_ISBN13 & ZBAR_ISBN10
                   config: ZBAR_CFG_ENABLE
                       to: 1];
    
    NSArray *ary=[reader.view subviews];//这个方法主要是去掉里面title 的button按钮的
    UIView *readerSubview=[ary objectAtIndex:1];
    NSArray *ary11=[readerSubview subviews];
    UIToolbar *tooB=[ary11 objectAtIndex:0];
    tooB.backgroundColor=[UIColor whiteColor];
    NSArray *ary22=[tooB subviews];
    UIButton *btn=[ary22 objectAtIndex:3];
    btn.hidden=YES;
    
    UIView *bgview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
    //bgview.alpha = 0.3;
    bgview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"zz.png"]];加一个全屏的框
    [reader.view addSubview:bgview];
    
    [self presentViewController:reader animated:YES completion:nil];
    
    
    
}
- (void) imagePickerController: (UIImagePickerController*) reader

 didFinishPickingMediaWithInfo: (NSDictionary*) info

{
    // 得到条形码结果
    id<NSFastEnumeration> results =
    
    [info objectForKey: ZBarReaderControllerResults];
    ZBarSymbol *symbol = nil;
    
    for(symbol in results)
        // EXAMPLE: just grab the first barcode
        break;
    
    // 将获得到条形码显示到我们的界面上
    
    textFields.text = symbol.data;
    
    // 扫描时的图片显示到我们的界面上
    //    resultImage.backgroundColor = [UIColor colorWithPatternImage:[info objectForKey: UIImagePickerControllerOriginalImage]];
    //    resultImage = [info objectForKey: UIImagePickerControllerOriginalImage];
    
    // 扫描界面退出
    
    //    [reader dismissModalViewControllerAnimated: YES];
//    [self performSelector:@selector(jianPanSearch) withObject:Nil afterDelay:0];

    [self dismissViewControllerAnimated:NO completion:nil];
    [self jianPanSearch];
    
}

5 实现九宫格的button,或者各种uiview 的实现简单的算法实现:

  int width = scroll.frame.size.width/4;
    for (int i=0; i<arrysImage.count; i++) {
        int t=i/4;//t是行数,d是列数
        int d=fmod(i, 4);
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(width*d +d*5+10, 300 * t+t*50, 225,300)];
        btn.tag=i+5000;
        [btn addTarget:self action:@selector(imageClcik:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:btn];
        [btn setImage:[UIImage imageWithData:[DataPist stringToByte:imageNames]] forState:UIControlStateNormal];
    }

6 实现简单的上来刷新,用的也是EGORefreshTableHeaderView,这个比较简单的,就是先初始化,然后调用那几个方法,

//此方法是开始读取数据
- (void)reloadTableViewDataSource{
    
    //  should be calling your tableviews data source model to reload
    //  put here just for demo
    _reloading = YES;
    NSLog(@"star");
    number = arrysImage.count;
//    NSLog(@"%d",number);
    //打开线程,读取网络图片
    [NSThread detachNewThreadSelector:@selector(requestLoadData) toTarget:self withObject:nil];
 
}

//此方法是结束读取数据 结束读取数据在是在要显示的 view 的显示后面方法
- (void)doneLoadingTableViewData{
    
    //  model should call this when its done loading
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:scroll];
    NSLog(@"end");
}
#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

        [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];

 
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    [self reloadTableViewDataSource];
    //[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5];
    
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
    return _reloading; // should return if data source model is reloading
    
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    return [NSDate date]; // should return date data source was last changed
    
}

还有一个就是加载数据后,显示在页面的view要调用  [scroll setContentSize:CGSizeMake(0,350*(arrysImage.count/4))];
   _refreshHeaderView.frame=CGRectMake(0, scroll.contentSize.height, 1024, 700);,这个比较麻烦的就是_refreshHeaderView最后位置的判断,

还有一个问题就是数据的更新请求数据arrayByAddingObjectsFromArray方法,实现

-(void)requestLoadData{
    NSString *post;
    
    
       post=[NSString stringWithFormat:@"%@/api/pull_down.php?page_number=%d&is_upcoming=%@",[DataPist shared].ipString,tag,type];

    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:post]];
    NSURLResponse *urlResponce=nil;
    NSError *error=nil;
    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponce error:&error];
    if (error) {
        UIAlertView *alter=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前网络不可用,请稍后再试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alter show];
        return;
    }

    NSArray   *arrys= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

    NSArray *currentArrys=[[NSArray alloc]initWithArray:arrys];
    
    if (arrys.count==0) {
         [self doneLoadingTableViewData];
//        [_refreshHeaderView removeFromSuperview];
        return;
    }
    
    arrysImage=[arrysImage arrayByAddingObjectsFromArray:currentArrys];//数组的组合添加在尾部
    [self performSelectorOnMainThread:@selector(initImage:) withObject:@"smallImage" waitUntilDone:YES];
    tag=tag+20;
}

 

7 在ios中操作plist实现删除,添加,操作的实现,主要是参考别人的方法,谢谢那位高手,后面有时间找出他的文章,贴出来,写在一个类了,里面.h文件

@interface SavePList : NSObject
+ (SavePList *)sharedInstance;
-(NSString*)getPlistPath:(NSString *)PlistName;
-(BOOL) isPlistFileExists:(NSString *)PlistName;
-(void)initPlist:(NSString *)plistName;
////判断key的书是否存在
-(BOOL)isBookExistsForKey:(NSString*)key name:(NSString *)plistName;
-(void)removeBookWithKey:(NSString *)key name:(NSString *)plistName;
-(void)deletePlist:(NSString *)plsitName;
-(void)writePlist:(NSMutableDictionary*)dictionary forKey:(NSString *)key  plsitName:(NSString *)plistName;
-(NSMutableDictionary*)readPlist:(NSString *)plistName;
-(void)readPlist:(NSMutableDictionary **)dictionary name:(NSString *)plistName;
-(void)replaceDictionary:(NSMutableDictionary *)newDictionary withDictionaryKey:(NSString *)key name:(NSString *)plistName;
@end

 .m文件

#import "SavePList.h"

@implementation SavePList
static SavePList *g_instance = nil;

+ (SavePList *)sharedInstance
{
    @synchronized(self) {
        if ( g_instance == nil ) {
            g_instance = [[self alloc] init];
        }
    }
    return g_instance;
}

//获得plist路径
-(NSString*)getPlistPath:(NSString *)PlistName{
//    //沙盒中的文件路径
//    NSArray *storeFilePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *doucumentsDirectiory = [storeFilePath objectAtIndex:0];
//    NSString *plistPath =[doucumentsDirectiory stringByAppendingPathComponent:@"data.plist"];       //根据需要更改文件名
//    return plistPath;
    //写入library
    NSString *fileNamepath;
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    
    NSString *pathNext = [NSString stringWithFormat:@"%@/Caches",path];
    
    if ([PlistName isEqualToString:@"dataOne"]) {
         fileNamepath=[pathNext stringByAppendingPathComponent:@"dataOne.plist"];
    }
    
    if ([PlistName isEqualToString:@"dataTwo"]) {
        fileNamepath=[pathNext stringByAppendingPathComponent:@"dataTwo.plist"];
    }
    if ([PlistName isEqualToString:@"dataThree"]) {
        fileNamepath=[pathNext stringByAppendingPathComponent:@"dataThree.plist"];
    }
    if ([PlistName isEqualToString:@"numpluse"]) {
        fileNamepath=[pathNext stringByAppendingPathComponent:@"numpluse.plist"];
    }
    
    return fileNamepath; 
}

//判断沙盒中名为plistname的文件是否存在
-(BOOL) isPlistFileExists:(NSString *)PlistName{
    
    NSString *plistPath =[[SavePList sharedInstance]getPlistPath:PlistName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if( [fileManager fileExistsAtPath:plistPath]== NO ) {
        NSLog(@"not exists");
        return NO;
    }else{
        return YES;
    }
    
}

-(void)initPlist:(NSString *)plistName{
    NSString *plistPath = [[SavePList sharedInstance] getPlistPath:plistName];
    
    //如果plist文件不存在,将工程中已建起的plist文件写入沙盒中
    if (! [[SavePList sharedInstance] isPlistFileExists:plistName]) {
        
        //从自己建立的plist文件 复制到沙盒中 ,方法一
        
        if ([plistName isEqualToString:@"dataOne"]) {
            NSError *error;
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *bundle = [[NSBundle mainBundle] pathForResource:@"dataOne" ofType:@"plist"];
            [fileManager copyItemAtPath:bundle toPath:plistPath error:&error];        }
        
        if ([plistName isEqualToString:@"dataTwo"]) {
            NSError *error;
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *bundle = [[NSBundle mainBundle] pathForResource:@"dataTwo" ofType:@"plist"];
            [fileManager copyItemAtPath:bundle toPath:plistPath error:&error];        }
        if ([plistName isEqualToString:@"dataThree"]) {
            NSError *error;
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *bundle = [[NSBundle mainBundle] pathForResource:@"dataThree" ofType:@"plist"];
            [fileManager copyItemAtPath:bundle toPath:plistPath error:&error];        }
        if ([plistName isEqualToString:@"numpluse"]) {
            NSError *error;
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *bundle = [[NSBundle mainBundle] pathForResource:@"numpluse" ofType:@"plist"];
            [fileManager copyItemAtPath:bundle toPath:plistPath error:&error];
        }

        
      
        
        //方法二
        //        NSString *path = [[NSBundle mainBundle] pathForResource:@"WBBooks"ofType:@"plist"];
        //        NSMutableDictionary *activityDics = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
        //        [activityDics writeToFile:plistPath atomically:YES];
    }
}


//判断key的书是否存在
-(BOOL)isBookExistsForKey:(NSString*)key name:(NSString *)plistName{
    
    NSString *plistPath = [[SavePList sharedInstance] getPlistPath:plistName];
    NSMutableDictionary *WBBooksDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    
    //根目录下存在名为bookname的字典
    if ([WBBooksDictionary objectForKey:key]) {
        return YES;
    }else{
        return NO;
    }
}


//根据key值删除对应书籍
-(void)removeBookWithKey:(NSString *)key name:(NSString *)plistName{
    
    NSString *plistPath = [[SavePList sharedInstance] getPlistPath:plistName];
    NSMutableDictionary *WBBooksDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    
    [WBBooksDictionary removeObjectForKey:key];
    [WBBooksDictionary writeToFile:plistPath atomically:YES]; //删除后重新写入
    NSLog(@"删除后%@",WBBooksDictionary);
    
}



//删除plistPath路径对应的文件
-(void)deletePlist:(NSString *)plsitName{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *plistPath = [[SavePList sharedInstance] getPlistPath:plsitName];
    [fileManager removeItemAtPath:plistPath error:nil];
    
}

//将dictionary写入plist文件,前提:dictionary已经准备好
-(void)writePlist:(NSMutableDictionary*)dictionary forKey:(NSString *)key  plsitName:(NSString *)plistName{
    
    NSMutableDictionary *plistDictionary = [[NSMutableDictionary alloc]init];
    
    //如果已存在则读取现有数据
    if ([[SavePList sharedInstance]isPlistFileExists:plistName]) {
        plistDictionary = [[SavePList sharedInstance]readPlist:plistName];
    }
    
    
    
    //增加一个数据
    [plistDictionary setValue:dictionary forKey:key]; //在plistDictionary增加一个key为...的value
    
    NSString *plistPath = [[SavePList sharedInstance] getPlistPath:plistName];
    NSLog(@"---%@",plistPath);
    
    if([plistDictionary writeToFile:plistPath atomically:YES]){
        NSLog(@"write ok!");
    }else{
        NSLog(@"ddd");
    }
    
    NSLog(@"plistDictionary=%@",plistDictionary);
}

//
-(NSMutableDictionary*)readPlist:(NSString *)plistName{
    
    NSString *plistPath = [[SavePList sharedInstance] getPlistPath:plistName];
    NSMutableDictionary *resultDictionary = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
    return resultDictionary;
}

//读取plist文件内容复制给dictionary   备用
-(void)readPlist:(NSMutableDictionary **)dictionary name:(NSString *)plistName{
    NSString *plistPath = [[SavePList sharedInstance] getPlistPath:plistName];
    *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
}

//更改一条数据,就是把dictionary内key重写
-(void)replaceDictionary:(NSMutableDictionary *)newDictionary withDictionaryKey:(NSString *)key name:(NSString *)plistName{
    
    [[SavePList sharedInstance]removeBookWithKey:key name:plistName];
    [[SavePList sharedInstance]writePlist:newDictionary forKey:key  plsitName:plistName];
    
}

-(NSInteger)getBooksCount:(NSString *)plistName{
    
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    dictionary = [[SavePList sharedInstance] readPlist:plistName];
    return [dictionary count];
    
}
@end

因为我建立了3个plist文件,所以再项目中建立了3个plist ,有的问题的是,我必须得在项目中把3个对应名字的空的plist先建号,然后才能用,这点当时因为没时间多想,就那样了,上面主要是添加,删除,操作了,,

8  遍历沙盒文件夹里面的所有文件方法

- (NSArray*) allFilesAtPath:(NSString*) dirString {
    //    NSMutableArray* array = [NSMutableArray arrayWithCapacity:10];
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSArray* tempArray = [fileMgr contentsOfDirectoryAtPath:dirString error:nil];
    return tempArray;
}

9 删除沙盒下面所有文件夹的方法

   //删除所有documents中的数据
    NSFileManager *fileManage = [NSFileManager defaultManager];
    NSString *myDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSArray *file = [fileManage subpathsOfDirectoryAtPath: myDirectory error:nil];
//    NSLog(@"%@",file);
    if (file.count != 0) {
        for (int i = 0; i < file.count; i++) {
            NSString *str = [NSString stringWithFormat:@"%@/%@",myDirectory,[file objectAtIndex:i]];
            [fileManage removeItemAtPath:str error:Nil];
        }
    }

10 在一个UIViewController里面点击按钮添加一个view

 detailChanPinView=[[DetailChanPinView alloc]initWithFrame:CGRectMake(0, 0, 1024, self.view.frame.size.height)];
    detailChanPinView.BigImageName=bigName;
    [UIView transitionWithView:self.view
                      duration:0.5
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        [self.view addSubview:detailChanPinView];
                        ;
                    }
                    completion:^(BOOL fisish){
                        
                    }];

当时主要问题是传值的问题,不知道怎么搞的一直无法传过去,最后用简单的方法     NSUserDefaults,和消息注册实现的,

先写这吧,后面在写了,



 

  

posted on 2013-09-02 15:38  songbai  阅读(713)  评论(0编辑  收藏  举报