2012年12月22日 星期六

certificate identity iPhone developer: appears more than once in the keychain.the code sign tool requires there only be one.


certificate identity iPhone developer: appears more than once in the keychain.the code sign tool requires there only be one.


最快的方式是,把key chia上的所有憑證和鑰匙都砍掉,全部重做。
原因是,自己砍,也沒有砍完全。

全部重做時,連.p12也都要重做,重做後,回到Http://developer.apple.com裡,把所有專案也都重新下載。
要記得在Actions > Edit > Modify > Certificates裡,開發者要勾選,Sumit後才下載新的專案憑證。
Development 和 Distribution都要做呦!~

2012年12月19日 星期三

Xcode一張憑證,多台MAC使用

1.先在原開發機上下載當初製作的開發憑證。


2.把輸出的.p12放在雲端上(EX:DropBox)
輸出檔名為.p12,附檔名不要亂改名字呦!~



3.因為這張憑證很重要,所以請給他一個密碼保護他。
等等在另一台電腦上,會要打開他來用,所以不能忘記呦。

4.填入登入系統的密碼,按下允許。


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

接下來換到另一台要當開發機的電腦上嘍!~

1.把「鑰匙圈存取」叫出來,檔案 > 輸入項目

2.到DropBox裡把剛剛存的.p12打開



3.輸入剛剛所填的保護檔案用的密碼。

4.這樣回到鑰匙圈主視窗後,在「憑證」裡就可以看到他了。







2012年12月18日 星期二

Xcode開發者憑證

1.先到鑰匙圈存取裡製作憑證。


2.輸入mail、名稱

3.按繼續做出.cer憑證。
4.到http://developer.apple.com登入開發者帳號
.在Certificates > Development,把剛剛的.cer上傳。

5.Distribution也把剛剛的.cer上傳哩



2012年12月13日 星期四

The model used to open the store is incompatible with the one used to create the store。


The model used to open the store is incompatible with the one used to create the store。
表示與目前現行版本的資料庫不同,要砍掉讓他自動產生新的。

連接JSON時,先看資料是Array?還是Dictionary?

連接JSON時,先看資料是Array?還是Dictionary?

[ Array

{Dictionary

JSON的資料
{ "NewBook": [ { "BookNo": "0104347 ", "BookName": "遇見街貓Bob ", "Author": "詹姆斯.伯恩 ", "Price": 290, "MemPrice": 229, "VipPrice": 220, "Url": "http://www.morningstar.com.tw/bookcomment-2.aspx?BOKNO=0104347", "ImgBig": "http://www.morningstar.com.tw/pic_m/0104347.jpg", "ImgSmall": "http://www.morningstar.com.tw/pic/0104347.jpg" },

    //最外層是Dictionary時,寫法用這樣。
     NSArray *json = [(NSDictionary *) [NSJSONSerialization JSONObjectWithData:responseData
     options:kNilOptions
     error:&error] objectForKey:@"NewBook"];
     
     
     
    
    
    //外層是Array就要用for去讀,每一輪讀取不同直,所以變數可以重複使用
    NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData //1
                                                    options:kNilOptions
                                                      error:&error];
    
    dataArray = [NSJSONSerialization JSONObjectWithData:responseData //1
                                                options:kNilOptions
                                                  error:&error];
   for (NSDictionary *obj in json) {
        NSString *bookname =[obj valueForKey:@"BookName"];
        NSString *author   =[obj valueForKey:@"Author"];
        NSNumber *price    =[obj valueForKey:@"Price"];
        NSNumber *memprice =[obj valueForKey:@"MemPrice"];
        NSNumber *vipprice =[obj valueForKey:@"VipPrice"];

2012年12月4日 星期二

用FireFox使用Sqlite


- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil) {
        return __persistentStoreCoordinator;
    }
    
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MorningStar.sqlite"];
    
    NSLog(@"DB Path = %@", storeURL);

印出本機資料庫路徑

iMac/Library/Application Support/iPhone Simulator/6.0/Applications/50E9B8DB-0486-4BE7-9F7E-A87A04837756/Documents/MorningStar.sqlite

開啟FireFox>SQLite Manager
用開啟舊檔方式,把MorningStar.sqlite拉進SQLite Manager裡面,就可以編輯本機的Sqlite了。



讓Xcode幫你產生core_data_sample.xcdatamodeld的.h .m檔


讓Xcode幫你產生core_data_sample.xcdatamodeld的.h  .m檔。

點選專案資料夾,右鍵>New File






選iOS>Core Data>NSManagedObject subclass,之後都下一步完成。



就會在專案資料夾中出現Focus.h  Focus.m





[CoreData]當本機還沒有產生sqlite時,這段程式先註解掉。


在AppDelegate.m裡,當本機還沒有產生sqlite時,這段程式先註解掉。
先讓前段程式執行生成。


 // 載入資料
    /*
    if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {
        NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"MorningStar" ofType:@"sqlite"]];
        NSError* err = nil;
        
        if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err]) {
            NSLog(@"Oops, could copy preloaded data");
        }
    }
    */

2012年10月16日 星期二

CoreData核心數據的基本概念和實例方法(2) TableView的展現

CoreData核心數據的基本概念和實例方法(2)
TableView的展現

.h

#import <UIKit/UIKit.h>


@interface CBTBViewController : UITableViewController

@property (nonatomic,strong) NSManagedObjectContext* managedObjectContext;

@property (strong) NSArray * CBArray; 
@property (strong) NSArray * CBImages;

@end


.m
#import <CoreData/CoreData.h>

#import "CBTBViewController.h"

#import "AppDelegate.h"

#import "CrowButterflies.h" //載入資料庫欄位

#import "CBViewController.h"



@interface CBTBViewController ()

@end

NSArray * CBArray;
NSArray * CBImages;

@implementation CBTBViewController

@synthesize managedObjectContext;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    CBArray = [[NSArray alloc] initWithObjects:@"斯氏紫斑蝶",@"端紫斑蝶",@"圓翅紫斑蝶",@"小紫斑蝶",@"大白斑蝶",@"黑脈樺斑蝶",@"樺斑蝶",@"淡紋青斑蝶",@"小紋青斑蝶",@"姬小青斑蝶",@"大青斑蝶",@"小青斑蝶", @"琉球青斑蝶",nil];
    CBImages = [[NSArray alloc] initWithObjects:@"crow01-icon.png",@"crow02-icon.png",@"crow03-icon.png",@"crow04-icon.png",@"crow05-icon.png",@"crow06-icon.png",@"crow07-icon.png",@"crow08-icon.png",@"crow09-icon.png",@"crow10-icon.png",@"crow11-icon.png",@"crow12-icon.png",@"crow13-icon.png", nil];

    // 載入 core data
    
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
        NSLog(@"After managedObjectContext: %@"managedObjectContext);
    }
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"CrowButterflies" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error;
    

//    NSLog(@"NSPredicate => %@", areaFilter);
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"crow_name != %@", @""];
    [fetchRequest setPredicate:predicate];

    
    CBArray = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
//    NSLog(@"%@", CBArray);
    
    // 結束 core data
    
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
//    return 0;
     return [CBArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";
    //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    CrowButterflies *c = [CBArray objectAtIndex:indexPath.row];
    cell.textLabel.text = c.crow_name;
    cell.detailTextLabel.text = c.crow_S_name;
//    cell.imageView.image = (NSString *) [CBArray objectAtIndex:indexPath.row];
    
    cell.imageView.image = [UIImage imageNamed: (NSString *) [CBImages objectAtIndex:indexPath.row]];
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSLog(@"prepareForSegue");
    
    NSIndexPath *path = [self.tableView indexPathForSelectedRow];
    CrowButterflies *p = [CBArray objectAtIndex:path.row];
    CBViewController *vc = [segue destinationViewController];
    vc.crowbutter = p;
}

@end










CoreData核心數據的基本概念和實例方法(1)



核心數據的基本概念和實例方法

建立專案時,勾選「Use Core Data」,AppDelegate.h,Xcode會自動宣告變數及方法在Class裡。
CoreData最重要的三個物件:
NSManagedObjectModel:資料庫的架構,包含資料表上各個欄位的屬性以及定義。
NSPersistentStoreCoordinator:此為資料庫連結,設定資料庫「名稱」、「位置」,及把資料更新到資料庫上都是使用coordinator.
NSManagedObjectContext:資料庫的內容,要取值、新增、刪除物件時,都是用到他的方法。

類別
用途 
方法 
NSManagedObject 
物件對象
管理屬性 
-entity
-valueForKey:
-setValue: forKey:
NSManagedObjectContext
資料庫內容
取得與儲存
-executeFetchRequest: error:
-save
NSManagedObjectModel
資料庫架構 
-entities
-fetchRequestTemplateForName:
-setFetchRequestTemplate: forName:
NSFetchRequest 
請求數據
-setEntity:
-setPredicate:
-setFetchBatchSize: 
NSPersistentStoreCoordinator 
儲存資料 
-addPersistentStoreWithType: configuration: URL: options: error:
-persistentStoreForURL: 
NSPredicate 
確定查詢條件 
+predicateWithFormat:
-evaluateWithObject: 


儲存資料到資料庫的方法- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{}
資料庫的儲存方式:
1.XML, XML具可讀性
2.SQLite, SQLite用於儲存大量資料時可節省空間
3.二進位或者是儲存於記憶體.可以依照自己的需求來決定, 二進位的存取非常快速但會使用大量記憶體所以不適用於操作大筆資料量


AppDelegate.h
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;  //資料庫內容取得與儲存
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;  //資料庫架構 
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;  //儲存資料

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

@end

=============================================================
AppDelegate.m
#import "AppDelegate.h"

#import "MainViewController.h"

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    MainViewController *controller = (MainViewController *)self.window.rootViewController;
    controller.managedObjectContext = self.managedObjectContext;
    return YES;
}
- (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.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext    //資料庫內容
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];   //儲存資料
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel  //資料庫架構
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"coredata" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator  //檢查app若沒有資料庫,就把coredata.sqlite塞給他。
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"coredata.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory     //返回程式目錄
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end